@forinda/kickjs 2.0.0 → 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/README.md +85 -584
- 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,113 @@
|
|
|
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 "reflect-metadata";
|
|
12
|
+
//#region src/core/cache.ts
|
|
13
|
+
const CACHEABLE_META = Symbol("kick:cacheable");
|
|
14
|
+
/**
|
|
15
|
+
* Default in-memory cache provider using a Map.
|
|
16
|
+
* Suitable for development and single-instance deployments.
|
|
17
|
+
* For multi-instance or production, use a Redis-backed provider.
|
|
18
|
+
*/
|
|
19
|
+
var MemoryCacheProvider = class {
|
|
20
|
+
store = /* @__PURE__ */ new Map();
|
|
21
|
+
async get(key) {
|
|
22
|
+
const entry = this.store.get(key);
|
|
23
|
+
if (!entry) return null;
|
|
24
|
+
if (entry.expiresAt <= Date.now()) {
|
|
25
|
+
this.store.delete(key);
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
return entry.data;
|
|
29
|
+
}
|
|
30
|
+
async set(key, value, ttlMs) {
|
|
31
|
+
this.store.set(key, {
|
|
32
|
+
data: value,
|
|
33
|
+
expiresAt: Date.now() + ttlMs
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
async del(key) {
|
|
37
|
+
this.store.delete(key);
|
|
38
|
+
}
|
|
39
|
+
async delByPrefix(prefix) {
|
|
40
|
+
for (const key of this.store.keys()) if (key.startsWith(prefix)) this.store.delete(key);
|
|
41
|
+
}
|
|
42
|
+
async shutdown() {
|
|
43
|
+
this.store.clear();
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
let _cacheProvider = new MemoryCacheProvider();
|
|
47
|
+
/**
|
|
48
|
+
* Set the global cache provider used by @Cacheable and @CacheEvict.
|
|
49
|
+
* Call this before bootstrapping your app.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* import { setCacheProvider } from '@forinda/kickjs-core'
|
|
54
|
+
* import { RedisCacheProvider } from './redis-cache'
|
|
55
|
+
*
|
|
56
|
+
* setCacheProvider(new RedisCacheProvider(redisClient))
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
function setCacheProvider(provider) {
|
|
60
|
+
_cacheProvider = provider;
|
|
61
|
+
}
|
|
62
|
+
/** Get the current cache provider */
|
|
63
|
+
function getCacheProvider() {
|
|
64
|
+
return _cacheProvider;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Cache the return value of a method for the specified TTL.
|
|
68
|
+
* Uses the globally registered CacheProvider (default: MemoryCacheProvider).
|
|
69
|
+
*
|
|
70
|
+
* Call `setCacheProvider()` to use Redis or any custom backend.
|
|
71
|
+
*
|
|
72
|
+
* @param ttl - Time-to-live in seconds (default: 60)
|
|
73
|
+
* @param options.key - Custom cache key prefix
|
|
74
|
+
*/
|
|
75
|
+
function Cacheable(ttl, options) {
|
|
76
|
+
return (_target, propertyKey, descriptor) => {
|
|
77
|
+
const original = descriptor.value;
|
|
78
|
+
const cacheTtl = (ttl ?? 60) * 1e3;
|
|
79
|
+
const keyPrefix = options?.key ?? String(propertyKey);
|
|
80
|
+
descriptor.value = async function(...args) {
|
|
81
|
+
const cacheKey = `${keyPrefix}:${JSON.stringify(args)}`;
|
|
82
|
+
const provider = getCacheProvider();
|
|
83
|
+
const cached = await provider.get(cacheKey);
|
|
84
|
+
if (cached !== null) return cached;
|
|
85
|
+
const result = await original.apply(this, args);
|
|
86
|
+
await provider.set(cacheKey, result, cacheTtl);
|
|
87
|
+
return result;
|
|
88
|
+
};
|
|
89
|
+
return descriptor;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Evict cached values matching a key prefix after the method executes.
|
|
94
|
+
* Works with any CacheProvider that implements `delByPrefix`.
|
|
95
|
+
*
|
|
96
|
+
* @param key - Cache key prefix to evict (matches the @Cacheable key)
|
|
97
|
+
*/
|
|
98
|
+
function CacheEvict(key) {
|
|
99
|
+
return (_target, _propertyKey, descriptor) => {
|
|
100
|
+
const original = descriptor.value;
|
|
101
|
+
descriptor.value = async function(...args) {
|
|
102
|
+
const result = await original.apply(this, args);
|
|
103
|
+
const provider = getCacheProvider();
|
|
104
|
+
if (provider.delByPrefix) await provider.delByPrefix(key);
|
|
105
|
+
return result;
|
|
106
|
+
};
|
|
107
|
+
return descriptor;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
111
|
+
export { CACHEABLE_META, CacheEvict, Cacheable, MemoryCacheProvider, getCacheProvider, setCacheProvider };
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=cache.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.mjs","names":[],"sources":["../../src/core/cache.ts"],"sourcesContent":["import 'reflect-metadata'\n\nconst CACHEABLE_META = Symbol('kick:cacheable')\n\n// ── CacheProvider Interface ─────────────────────────────────────────────\n\n/**\n * Abstract cache backend. Implement this interface to use Redis, Memcached,\n * or any other cache store with @Cacheable and @CacheEvict.\n *\n * @example\n * ```ts\n * class RedisCacheProvider implements CacheProvider {\n * private client: RedisClient\n * constructor(client: RedisClient) { this.client = client }\n * async get(key: string) {\n * const val = await this.client.get(key)\n * return val ? JSON.parse(val) : null\n * }\n * async set(key: string, value: any, ttlMs: number) {\n * await this.client.set(key, JSON.stringify(value), 'PX', ttlMs)\n * }\n * async del(key: string) { await this.client.del(key) }\n * async delByPrefix(prefix: string) {\n * const keys = await this.client.keys(prefix + '*')\n * if (keys.length) await this.client.del(...keys)\n * }\n * }\n * ```\n */\nexport interface CacheProvider {\n /** Retrieve a cached value. Return null if not found or expired. */\n get(key: string): Promise<any | null>\n /** Store a value with a TTL in milliseconds. */\n set(key: string, value: any, ttlMs: number): Promise<void>\n /** Delete a specific cache key. */\n del(key: string): Promise<void>\n /** Delete all keys matching a prefix. Used by @CacheEvict. */\n delByPrefix?(prefix: string): Promise<void>\n /** Optional cleanup on shutdown. */\n shutdown?(): Promise<void>\n}\n\n// ── Built-in Memory Provider ────────────────────────────────────────────\n\n/**\n * Default in-memory cache provider using a Map.\n * Suitable for development and single-instance deployments.\n * For multi-instance or production, use a Redis-backed provider.\n */\nexport class MemoryCacheProvider implements CacheProvider {\n private store = new Map<string, { data: any; expiresAt: number }>()\n\n async get(key: string): Promise<any | null> {\n const entry = this.store.get(key)\n if (!entry) return null\n if (entry.expiresAt <= Date.now()) {\n this.store.delete(key)\n return null\n }\n return entry.data\n }\n\n async set(key: string, value: any, ttlMs: number): Promise<void> {\n this.store.set(key, { data: value, expiresAt: Date.now() + ttlMs })\n }\n\n async del(key: string): Promise<void> {\n this.store.delete(key)\n }\n\n async delByPrefix(prefix: string): Promise<void> {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.store.delete(key)\n }\n }\n }\n\n async shutdown(): Promise<void> {\n this.store.clear()\n }\n}\n\n// ── Global Cache Registry ───────────────────────────────────────────────\n\nlet _cacheProvider: CacheProvider = new MemoryCacheProvider()\n\n/**\n * Set the global cache provider used by @Cacheable and @CacheEvict.\n * Call this before bootstrapping your app.\n *\n * @example\n * ```ts\n * import { setCacheProvider } from '@forinda/kickjs-core'\n * import { RedisCacheProvider } from './redis-cache'\n *\n * setCacheProvider(new RedisCacheProvider(redisClient))\n * ```\n */\nexport function setCacheProvider(provider: CacheProvider): void {\n _cacheProvider = provider\n}\n\n/** Get the current cache provider */\nexport function getCacheProvider(): CacheProvider {\n return _cacheProvider\n}\n\n// ── Cache Options ───────────────────────────────────────────────────────\n\nexport interface CacheOptions {\n /** Time-to-live in seconds (default: 60) */\n ttl?: number\n /** Cache key prefix (default: ClassName.methodName) */\n key?: string\n}\n\n// ── @Cacheable Decorator ────────────────────────────────────────────────\n\n/**\n * Cache the return value of a method for the specified TTL.\n * Uses the globally registered CacheProvider (default: MemoryCacheProvider).\n *\n * Call `setCacheProvider()` to use Redis or any custom backend.\n *\n * @param ttl - Time-to-live in seconds (default: 60)\n * @param options.key - Custom cache key prefix\n */\nexport function Cacheable(ttl?: number, options?: { key?: string }): MethodDecorator {\n return (_target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n const cacheTtl = (ttl ?? 60) * 1000\n const keyPrefix = options?.key ?? String(propertyKey)\n\n descriptor.value = async function (...args: any[]) {\n const cacheKey = `${keyPrefix}:${JSON.stringify(args)}`\n const provider = getCacheProvider()\n\n const cached = await provider.get(cacheKey)\n if (cached !== null) {\n return cached\n }\n\n const result = await original.apply(this, args)\n await provider.set(cacheKey, result, cacheTtl)\n return result\n }\n\n return descriptor\n }\n}\n\n// ── @CacheEvict Decorator ───────────────────────────────────────────────\n\n/**\n * Evict cached values matching a key prefix after the method executes.\n * Works with any CacheProvider that implements `delByPrefix`.\n *\n * @param key - Cache key prefix to evict (matches the @Cacheable key)\n */\nexport function CacheEvict(key: string): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n\n descriptor.value = async function (...args: any[]) {\n const result = await original.apply(this, args)\n const provider = getCacheProvider()\n if (provider.delByPrefix) {\n await provider.delByPrefix(key)\n }\n return result\n }\n\n return descriptor\n }\n}\n\nexport { CACHEABLE_META }\n"],"mappings":";;;;;;;;;;;;AAEA,MAAM,iBAAiB,OAAO,iBAAiB;;;;;;AAgD/C,IAAa,sBAAb,MAA0D;CACxD,wBAAgB,IAAI,KAA+C;CAEnE,MAAM,IAAI,KAAkC;EAC1C,MAAM,QAAQ,KAAK,MAAM,IAAI,IAAI;AACjC,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,MAAM,aAAa,KAAK,KAAK,EAAE;AACjC,QAAK,MAAM,OAAO,IAAI;AACtB,UAAO;;AAET,SAAO,MAAM;;CAGf,MAAM,IAAI,KAAa,OAAY,OAA8B;AAC/D,OAAK,MAAM,IAAI,KAAK;GAAE,MAAM;GAAO,WAAW,KAAK,KAAK,GAAG;GAAO,CAAC;;CAGrE,MAAM,IAAI,KAA4B;AACpC,OAAK,MAAM,OAAO,IAAI;;CAGxB,MAAM,YAAY,QAA+B;AAC/C,OAAK,MAAM,OAAO,KAAK,MAAM,MAAM,CACjC,KAAI,IAAI,WAAW,OAAO,CACxB,MAAK,MAAM,OAAO,IAAI;;CAK5B,MAAM,WAA0B;AAC9B,OAAK,MAAM,OAAO;;;AAMtB,IAAI,iBAAgC,IAAI,qBAAqB;;;;;;;;;;;;;AAc7D,SAAgB,iBAAiB,UAA+B;AAC9D,kBAAiB;;;AAInB,SAAgB,mBAAkC;AAChD,QAAO;;;;;;;;;;;AAuBT,SAAgB,UAAU,KAAc,SAA6C;AACnF,SAAQ,SAAS,aAAa,eAAmC;EAC/D,MAAM,WAAW,WAAW;EAC5B,MAAM,YAAY,OAAO,MAAM;EAC/B,MAAM,YAAY,SAAS,OAAO,OAAO,YAAY;AAErD,aAAW,QAAQ,eAAgB,GAAG,MAAa;GACjD,MAAM,WAAW,GAAG,UAAU,GAAG,KAAK,UAAU,KAAK;GACrD,MAAM,WAAW,kBAAkB;GAEnC,MAAM,SAAS,MAAM,SAAS,IAAI,SAAS;AAC3C,OAAI,WAAW,KACb,QAAO;GAGT,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM,KAAK;AAC/C,SAAM,SAAS,IAAI,UAAU,QAAQ,SAAS;AAC9C,UAAO;;AAGT,SAAO;;;;;;;;;AAYX,SAAgB,WAAW,KAA8B;AACvD,SAAQ,SAAS,cAAc,eAAmC;EAChE,MAAM,WAAW,WAAW;AAE5B,aAAW,QAAQ,eAAgB,GAAG,MAAa;GACjD,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM,KAAK;GAC/C,MAAM,WAAW,kBAAkB;AACnC,OAAI,SAAS,YACX,OAAM,SAAS,YAAY,IAAI;AAEjC,UAAO;;AAGT,SAAO"}
|
|
@@ -0,0 +1,426 @@
|
|
|
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 { METADATA, Scope } from "./interfaces.mjs";
|
|
12
|
+
import { createLogger } from "./logger.mjs";
|
|
13
|
+
import { i as getMetaRecord, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, r as getMetaMap, t as getClassMeta } from "../metadata-fmvikBA0.mjs";
|
|
14
|
+
import "reflect-metadata";
|
|
15
|
+
//#region src/core/container.ts
|
|
16
|
+
const log = createLogger("Container");
|
|
17
|
+
/** Create a Registration with observability defaults */
|
|
18
|
+
function createReg(fields) {
|
|
19
|
+
return {
|
|
20
|
+
kind: "unknown",
|
|
21
|
+
resolveCount: 0,
|
|
22
|
+
postConstructStatus: "skipped",
|
|
23
|
+
dependencies: [],
|
|
24
|
+
...fields
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Format a token for display in error messages */
|
|
28
|
+
function tokenName(token) {
|
|
29
|
+
if (typeof token === "symbol") return token.toString();
|
|
30
|
+
return token?.name || String(token);
|
|
31
|
+
}
|
|
32
|
+
function getPersistentStore() {
|
|
33
|
+
if (!globalThis.__kickjs_persistent) globalThis.__kickjs_persistent = {
|
|
34
|
+
factories: [],
|
|
35
|
+
instances: [],
|
|
36
|
+
resolvedInstances: /* @__PURE__ */ new Map()
|
|
37
|
+
};
|
|
38
|
+
return globalThis.__kickjs_persistent;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Inversion-of-Control (IoC) container that manages dependency registration,
|
|
42
|
+
* resolution, and lifecycle. Implements the Singleton pattern so all parts of
|
|
43
|
+
* the application share a single container instance.
|
|
44
|
+
*
|
|
45
|
+
* Supports constructor injection, property injection (@Autowired),
|
|
46
|
+
* factory registrations, and lifecycle hooks (@PostConstruct).
|
|
47
|
+
*
|
|
48
|
+
* Persistent state (DB connections, Redis, etc.) is stored on globalThis so
|
|
49
|
+
* it survives both Container.reset() and Vite module re-evaluation.
|
|
50
|
+
*/
|
|
51
|
+
var Container = class Container {
|
|
52
|
+
static instance;
|
|
53
|
+
registrations = /* @__PURE__ */ new Map();
|
|
54
|
+
resolving = /* @__PURE__ */ new Set();
|
|
55
|
+
changeListeners = /* @__PURE__ */ new Set();
|
|
56
|
+
pendingChanges = [];
|
|
57
|
+
notifyTimer = null;
|
|
58
|
+
static DEBOUNCE_MS = 50;
|
|
59
|
+
/** Callback set by the decorators module to flush pending registrations */
|
|
60
|
+
static _onReady = null;
|
|
61
|
+
/** Callback invoked on reset so decorators can update their container reference */
|
|
62
|
+
static _onReset = null;
|
|
63
|
+
/**
|
|
64
|
+
* Environment resolver for @Value decorator. Set by @forinda/kickjs-config
|
|
65
|
+
* to return Zod-validated, type-coerced env values instead of raw process.env strings.
|
|
66
|
+
*/
|
|
67
|
+
static _envResolver = null;
|
|
68
|
+
/**
|
|
69
|
+
* Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http
|
|
70
|
+
* to return the current request's AsyncLocalStorage store.
|
|
71
|
+
* Returns { instances: Map, values: Map } or null if outside a request.
|
|
72
|
+
*/
|
|
73
|
+
static _requestStoreProvider = null;
|
|
74
|
+
static getInstance() {
|
|
75
|
+
if (!Container.instance) Container.instance = new Container();
|
|
76
|
+
if (Container._onReady) {
|
|
77
|
+
Container._onReady(Container.instance);
|
|
78
|
+
Container._onReady = null;
|
|
79
|
+
}
|
|
80
|
+
return Container.instance;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Resets the container by replacing the singleton with a fresh instance.
|
|
84
|
+
* Persistent registrations (DB, Redis, etc.) are replayed from globalThis
|
|
85
|
+
* so they survive both reset() and Vite module re-evaluation.
|
|
86
|
+
*/
|
|
87
|
+
static reset() {
|
|
88
|
+
Container.instance = new Container();
|
|
89
|
+
Container._onReset?.(Container.instance);
|
|
90
|
+
const store = getPersistentStore();
|
|
91
|
+
for (const { token, factory, scope } of store.factories) if (!Container.instance.has(token)) {
|
|
92
|
+
const name = tokenName(token);
|
|
93
|
+
const existing = store.resolvedInstances.get(name);
|
|
94
|
+
Container.instance.registrations.set(token, createReg({
|
|
95
|
+
target: Object,
|
|
96
|
+
scope,
|
|
97
|
+
factory,
|
|
98
|
+
kind: "factory",
|
|
99
|
+
instance: existing,
|
|
100
|
+
resolveCount: existing ? 1 : 0,
|
|
101
|
+
postConstructStatus: existing ? "completed" : "skipped"
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
for (const { token, instance } of store.instances) if (!Container.instance.has(token)) Container.instance.registrations.set(token, createReg({
|
|
105
|
+
target: instance.constructor,
|
|
106
|
+
scope: Scope.SINGLETON,
|
|
107
|
+
instance,
|
|
108
|
+
kind: "instance",
|
|
109
|
+
postConstructStatus: "completed",
|
|
110
|
+
resolveCount: 1
|
|
111
|
+
}));
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Create an isolated container instance (not the global singleton).
|
|
115
|
+
* Useful for concurrent tests that must not share DI state.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* const container = Container.create()
|
|
120
|
+
* container.register(UserService, UserService)
|
|
121
|
+
* const svc = container.resolve(UserService)
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
static create() {
|
|
125
|
+
return new Container();
|
|
126
|
+
}
|
|
127
|
+
/** Register a class constructor under the given token */
|
|
128
|
+
register(token, target, scope = Scope.SINGLETON) {
|
|
129
|
+
const kind = getClassMeta(METADATA.CLASS_KIND, target, "unknown");
|
|
130
|
+
const reg = createReg({
|
|
131
|
+
target,
|
|
132
|
+
scope,
|
|
133
|
+
kind,
|
|
134
|
+
dependencies: this.extractDependencies(target)
|
|
135
|
+
});
|
|
136
|
+
this.registrations.set(token, reg);
|
|
137
|
+
if (typeof token === "function" && token.name) this.registrations.set(`__hmr__${token.name}`, reg);
|
|
138
|
+
this.emit(tokenName(token), "registered", kind);
|
|
139
|
+
}
|
|
140
|
+
/** Register a factory function under the given token */
|
|
141
|
+
registerFactory(token, factory, scope = Scope.SINGLETON) {
|
|
142
|
+
const store = getPersistentStore();
|
|
143
|
+
const name = tokenName(token);
|
|
144
|
+
const factoryUnchanged = store.factories.find((r) => tokenName(r.token) === name)?.factory === factory;
|
|
145
|
+
const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : void 0;
|
|
146
|
+
if (!factoryUnchanged) store.resolvedInstances.delete(name);
|
|
147
|
+
this.registrations.set(token, createReg({
|
|
148
|
+
target: Object,
|
|
149
|
+
scope,
|
|
150
|
+
factory,
|
|
151
|
+
kind: "factory",
|
|
152
|
+
instance: existingInstance,
|
|
153
|
+
resolveCount: existingInstance ? 1 : 0,
|
|
154
|
+
postConstructStatus: existingInstance ? "completed" : "skipped"
|
|
155
|
+
}));
|
|
156
|
+
const idx = store.factories.findIndex((r) => tokenName(r.token) === name);
|
|
157
|
+
if (idx >= 0) store.factories[idx] = {
|
|
158
|
+
token,
|
|
159
|
+
factory,
|
|
160
|
+
scope
|
|
161
|
+
};
|
|
162
|
+
else store.factories.push({
|
|
163
|
+
token,
|
|
164
|
+
factory,
|
|
165
|
+
scope
|
|
166
|
+
});
|
|
167
|
+
this.emit(name, "registered", "factory");
|
|
168
|
+
}
|
|
169
|
+
/** Register a pre-constructed singleton instance */
|
|
170
|
+
registerInstance(token, instance) {
|
|
171
|
+
const store = getPersistentStore();
|
|
172
|
+
const name = tokenName(token);
|
|
173
|
+
this.registrations.set(token, createReg({
|
|
174
|
+
target: instance.constructor,
|
|
175
|
+
scope: Scope.SINGLETON,
|
|
176
|
+
instance,
|
|
177
|
+
kind: "instance",
|
|
178
|
+
postConstructStatus: "completed",
|
|
179
|
+
resolveCount: 1,
|
|
180
|
+
firstResolvedAt: Date.now(),
|
|
181
|
+
lastResolvedAt: Date.now()
|
|
182
|
+
}));
|
|
183
|
+
store.resolvedInstances.set(name, instance);
|
|
184
|
+
const idx = store.instances.findIndex((r) => tokenName(r.token) === name);
|
|
185
|
+
if (idx >= 0) store.instances[idx] = {
|
|
186
|
+
token,
|
|
187
|
+
instance
|
|
188
|
+
};
|
|
189
|
+
else store.instances.push({
|
|
190
|
+
token,
|
|
191
|
+
instance
|
|
192
|
+
});
|
|
193
|
+
this.emit(name, "registered", "instance");
|
|
194
|
+
}
|
|
195
|
+
/** Check if a binding exists for the given token */
|
|
196
|
+
has(token) {
|
|
197
|
+
return this.registrations.has(token);
|
|
198
|
+
}
|
|
199
|
+
/** Return a snapshot of all registered tokens with their scope and instantiation status */
|
|
200
|
+
getRegistrations() {
|
|
201
|
+
const entries = [];
|
|
202
|
+
for (const [token, reg] of this.registrations) entries.push({
|
|
203
|
+
token: tokenName(token),
|
|
204
|
+
scope: reg.scope,
|
|
205
|
+
kind: reg.kind,
|
|
206
|
+
instantiated: reg.scope === Scope.SINGLETON ? reg.instance !== void 0 : reg.resolveCount > 0,
|
|
207
|
+
resolveCount: reg.resolveCount,
|
|
208
|
+
lastResolvedAt: reg.lastResolvedAt,
|
|
209
|
+
firstResolvedAt: reg.firstResolvedAt,
|
|
210
|
+
resolveDurationMs: reg.resolveDurationMs,
|
|
211
|
+
postConstructStatus: reg.postConstructStatus,
|
|
212
|
+
dependencies: reg.dependencies
|
|
213
|
+
});
|
|
214
|
+
return entries;
|
|
215
|
+
}
|
|
216
|
+
/** Resolve a dependency by its token */
|
|
217
|
+
resolve(token) {
|
|
218
|
+
let reg = this.registrations.get(token);
|
|
219
|
+
if (!reg && typeof token === "function" && token.name) reg = this.registrations.get(`__hmr__${token.name}`);
|
|
220
|
+
if (!reg) throw new Error(`No binding found for: ${tokenName(token)}`);
|
|
221
|
+
if (reg.scope === Scope.SINGLETON && reg.instance !== void 0) {
|
|
222
|
+
reg.resolveCount++;
|
|
223
|
+
reg.lastResolvedAt = Date.now();
|
|
224
|
+
return reg.instance;
|
|
225
|
+
}
|
|
226
|
+
if (reg.scope === Scope.REQUEST) {
|
|
227
|
+
if (!Container._requestStoreProvider) throw new Error(`Cannot resolve REQUEST-scoped "${tokenName(token)}": no request store provider configured. Ensure requestScopeMiddleware() is in your middleware pipeline.`);
|
|
228
|
+
const store = Container._requestStoreProvider();
|
|
229
|
+
if (!store) throw new Error(`Cannot resolve REQUEST-scoped "${tokenName(token)}" outside an HTTP request context.`);
|
|
230
|
+
if (store.values.has(token)) {
|
|
231
|
+
reg.resolveCount++;
|
|
232
|
+
reg.lastResolvedAt = Date.now();
|
|
233
|
+
return store.values.get(token);
|
|
234
|
+
}
|
|
235
|
+
if (store.instances.has(token)) {
|
|
236
|
+
reg.resolveCount++;
|
|
237
|
+
reg.lastResolvedAt = Date.now();
|
|
238
|
+
return store.instances.get(token);
|
|
239
|
+
}
|
|
240
|
+
const start = performance.now();
|
|
241
|
+
const instance = this.createInstance(reg);
|
|
242
|
+
reg.resolveDurationMs = performance.now() - start;
|
|
243
|
+
reg.resolveCount++;
|
|
244
|
+
reg.lastResolvedAt = Date.now();
|
|
245
|
+
if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
|
|
246
|
+
store.instances.set(token, instance);
|
|
247
|
+
return instance;
|
|
248
|
+
}
|
|
249
|
+
if (reg.factory) {
|
|
250
|
+
const start = performance.now();
|
|
251
|
+
const instance = reg.factory();
|
|
252
|
+
reg.resolveDurationMs = performance.now() - start;
|
|
253
|
+
reg.resolveCount++;
|
|
254
|
+
reg.lastResolvedAt = Date.now();
|
|
255
|
+
if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
|
|
256
|
+
if (reg.scope === Scope.SINGLETON) {
|
|
257
|
+
reg.instance = instance;
|
|
258
|
+
getPersistentStore().resolvedInstances.set(tokenName(token), instance);
|
|
259
|
+
}
|
|
260
|
+
return instance;
|
|
261
|
+
}
|
|
262
|
+
if (this.resolving.has(token)) {
|
|
263
|
+
const chain = [...this.resolving].map(tokenName);
|
|
264
|
+
chain.push(tokenName(token));
|
|
265
|
+
throw new Error(`Circular dependency detected: ${chain.join(" -> ")}`);
|
|
266
|
+
}
|
|
267
|
+
this.resolving.add(token);
|
|
268
|
+
try {
|
|
269
|
+
const start = performance.now();
|
|
270
|
+
const instance = this.createInstance(reg);
|
|
271
|
+
reg.resolveDurationMs = performance.now() - start;
|
|
272
|
+
reg.resolveCount++;
|
|
273
|
+
reg.lastResolvedAt = Date.now();
|
|
274
|
+
if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now();
|
|
275
|
+
if (reg.scope === Scope.SINGLETON) reg.instance = instance;
|
|
276
|
+
return instance;
|
|
277
|
+
} finally {
|
|
278
|
+
this.resolving.delete(token);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/** Lifecycle hook called during Application.setup() after module registration */
|
|
282
|
+
bootstrap() {}
|
|
283
|
+
/**
|
|
284
|
+
* Subscribe to container changes. Returns an unsubscribe function.
|
|
285
|
+
*
|
|
286
|
+
* Changes are batched (50ms debounce) so bulk operations like
|
|
287
|
+
* `kick g module` creating 10+ files emit ONE batch, not 10 events.
|
|
288
|
+
*
|
|
289
|
+
* Any adapter can subscribe:
|
|
290
|
+
* - SwaggerAdapter: re-build spec when controllers change
|
|
291
|
+
* - DevToolsAdapter: push SSE events to dashboard
|
|
292
|
+
* - WsAdapter: re-discover namespaces when controllers change
|
|
293
|
+
* - OtelAdapter: emit tracing spans for DI resolution
|
|
294
|
+
* - Custom user adapters
|
|
295
|
+
*
|
|
296
|
+
* @example
|
|
297
|
+
* ```ts
|
|
298
|
+
* const unsub = container.onChange((changes) => {
|
|
299
|
+
* for (const c of changes) {
|
|
300
|
+
* console.log(`${c.event}: ${c.token} (${c.kind})`)
|
|
301
|
+
* }
|
|
302
|
+
* })
|
|
303
|
+
* // later:
|
|
304
|
+
* unsub()
|
|
305
|
+
* ```
|
|
306
|
+
*/
|
|
307
|
+
onChange(callback) {
|
|
308
|
+
this.changeListeners.add(callback);
|
|
309
|
+
return () => this.changeListeners.delete(callback);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Invalidate a specific registration. Clears the cached instance so the
|
|
313
|
+
* next resolve() creates a fresh one. Also invalidates dependents
|
|
314
|
+
* (anything that injected this token) by walking the dependency graph.
|
|
315
|
+
*
|
|
316
|
+
* Called by the Vite HMR plugin when a module file changes.
|
|
317
|
+
* Skips persistent registrations (DB connections, etc.).
|
|
318
|
+
*/
|
|
319
|
+
invalidate(token) {
|
|
320
|
+
const name = tokenName(token);
|
|
321
|
+
const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`);
|
|
322
|
+
if (!reg) return;
|
|
323
|
+
if (getPersistentStore().resolvedInstances.has(name)) return;
|
|
324
|
+
reg.instance = void 0;
|
|
325
|
+
reg.resolveCount = 0;
|
|
326
|
+
reg.postConstructStatus = "skipped";
|
|
327
|
+
this.emit(name, "invalidated", reg.kind);
|
|
328
|
+
for (const [depToken, depReg] of this.registrations) if (depReg.dependencies.includes(name)) this.invalidate(depToken);
|
|
329
|
+
}
|
|
330
|
+
/** Batch-emit a change event (debounced, flushed after 50ms of quiet) */
|
|
331
|
+
emit(token, event, kind) {
|
|
332
|
+
this.pendingChanges.push({
|
|
333
|
+
token,
|
|
334
|
+
event,
|
|
335
|
+
kind,
|
|
336
|
+
timestamp: Date.now()
|
|
337
|
+
});
|
|
338
|
+
if (this.notifyTimer) clearTimeout(this.notifyTimer);
|
|
339
|
+
this.notifyTimer = setTimeout(() => {
|
|
340
|
+
const batch = this.pendingChanges.splice(0);
|
|
341
|
+
if (batch.length === 0) return;
|
|
342
|
+
for (const listener of this.changeListeners) try {
|
|
343
|
+
listener(batch);
|
|
344
|
+
} catch {}
|
|
345
|
+
}, Container.DEBOUNCE_MS);
|
|
346
|
+
}
|
|
347
|
+
/** Flush pending change events immediately (useful in tests) */
|
|
348
|
+
flushChanges() {
|
|
349
|
+
if (this.notifyTimer) {
|
|
350
|
+
clearTimeout(this.notifyTimer);
|
|
351
|
+
this.notifyTimer = null;
|
|
352
|
+
}
|
|
353
|
+
const batch = this.pendingChanges.splice(0);
|
|
354
|
+
if (batch.length === 0) return;
|
|
355
|
+
for (const listener of this.changeListeners) try {
|
|
356
|
+
listener(batch);
|
|
357
|
+
} catch {}
|
|
358
|
+
}
|
|
359
|
+
createInstance(reg) {
|
|
360
|
+
const args = getClassMeta(METADATA.PARAM_TYPES, reg.target, []).map((paramType, index) => {
|
|
361
|
+
const token = getMetaRecord(METADATA.INJECT, reg.target)[index] || paramType;
|
|
362
|
+
if (reg.scope === Scope.SINGLETON) {
|
|
363
|
+
const depReg = this.registrations.get(token);
|
|
364
|
+
if (depReg && depReg.scope === Scope.REQUEST) throw new Error(`Cannot inject REQUEST-scoped "${tokenName(token)}" into SINGLETON "${tokenName(reg.target)}". Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`);
|
|
365
|
+
}
|
|
366
|
+
return this.resolve(token);
|
|
367
|
+
});
|
|
368
|
+
const instance = new reg.target(...args);
|
|
369
|
+
this.injectProperties(instance, reg.target);
|
|
370
|
+
const postConstruct = getClassMetaOrUndefined(METADATA.POST_CONSTRUCT, reg.target.prototype);
|
|
371
|
+
if (postConstruct && typeof instance[postConstruct] === "function") try {
|
|
372
|
+
const result = instance[postConstruct]();
|
|
373
|
+
if (result && typeof result.then === "function") {
|
|
374
|
+
reg.postConstructStatus = "pending";
|
|
375
|
+
result.then(() => {
|
|
376
|
+
reg.postConstructStatus = "completed";
|
|
377
|
+
}).catch(() => {
|
|
378
|
+
reg.postConstructStatus = "failed";
|
|
379
|
+
});
|
|
380
|
+
log.warn(`@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise but the container is synchronous. The async operation will not be awaited.`);
|
|
381
|
+
} else reg.postConstructStatus = "completed";
|
|
382
|
+
} catch (err) {
|
|
383
|
+
reg.postConstructStatus = "failed";
|
|
384
|
+
log.error(err, `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`);
|
|
385
|
+
}
|
|
386
|
+
return instance;
|
|
387
|
+
}
|
|
388
|
+
/** Extract dependency token names from constructor metadata */
|
|
389
|
+
extractDependencies(target) {
|
|
390
|
+
const paramTypes = getClassMeta(METADATA.PARAM_TYPES, target, []);
|
|
391
|
+
const injectTokens = getMetaRecord(METADATA.INJECT, target);
|
|
392
|
+
return paramTypes.map((type, index) => {
|
|
393
|
+
return tokenName(injectTokens[index] || type);
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
injectProperties(instance, target) {
|
|
397
|
+
const autowiredProps = getMetaMap(METADATA.AUTOWIRED, target.prototype);
|
|
398
|
+
for (const [prop, token] of autowiredProps) {
|
|
399
|
+
const resolvedToken = token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop);
|
|
400
|
+
if (resolvedToken) Object.defineProperty(instance, prop, {
|
|
401
|
+
get: () => this.resolve(resolvedToken),
|
|
402
|
+
enumerable: true,
|
|
403
|
+
configurable: true
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
const valueProps = getMetaMap(METADATA.VALUE, target.prototype);
|
|
407
|
+
for (const [prop, config] of valueProps) Object.defineProperty(instance, prop, {
|
|
408
|
+
get() {
|
|
409
|
+
if (Container._envResolver) {
|
|
410
|
+
const val = Container._envResolver(config.envKey);
|
|
411
|
+
if (val !== void 0) return val;
|
|
412
|
+
}
|
|
413
|
+
const val = process.env[config.envKey];
|
|
414
|
+
if (val !== void 0) return val;
|
|
415
|
+
if (config.defaultValue !== void 0) return config.defaultValue;
|
|
416
|
+
throw new Error(`@Value('${config.envKey}'): Environment variable "${config.envKey}" is not set and no default was provided.`);
|
|
417
|
+
},
|
|
418
|
+
enumerable: true,
|
|
419
|
+
configurable: true
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
//#endregion
|
|
424
|
+
export { Container, tokenName };
|
|
425
|
+
|
|
426
|
+
//# sourceMappingURL=container.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"container.mjs","names":[],"sources":["../../src/core/container.ts"],"sourcesContent":["import 'reflect-metadata'\nimport {\n Constructor,\n Scope,\n METADATA,\n type ClassKind,\n type PostConstructStatus,\n} from './interfaces'\nimport { createLogger } from './logger'\nimport {\n getClassMeta,\n getClassMetaOrUndefined,\n getMetaMap,\n getMetaRecord,\n getMethodMetaOrUndefined,\n} from './metadata'\n\nconst log = createLogger('Container')\n\n/** Internal registration entry that tracks how a dependency should be resolved */\ninterface Registration {\n target: Constructor\n scope: Scope\n instance?: any\n factory?: () => any\n // Observability fields\n kind: ClassKind\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n}\n\n/** Create a Registration with observability defaults */\nfunction createReg(\n fields: Partial<Registration> & Pick<Registration, 'target' | 'scope'>,\n): Registration {\n return {\n kind: 'unknown',\n resolveCount: 0,\n postConstructStatus: 'skipped',\n dependencies: [],\n ...fields,\n }\n}\n\n/** Format a token for display in error messages */\nexport function tokenName(token: any): string {\n if (typeof token === 'symbol') return token.toString()\n return token?.name || String(token)\n}\n\n// ── Persistent Store ────────────────────────────────────────────────────\n// globalThis-based storage that survives BOTH Container.reset() AND Vite's\n// ssrLoadModule() re-evaluation. When Vite re-evaluates a module, the\n// Container class gets a new identity (new statics). But globalThis persists.\n//\n// This is how DB connections, Redis clients, WsAdapter instances, and any\n// other stateful bindings survive HMR without being dropped.\n//\n// Pattern from: React Router (globalThis for state), Vinxi (globalThis.app)\n\n// ── Change Event System ─────────────────────────────────────────────────\n// Batched (50ms debounce) so `kick g module` creating 10+ files emits ONE\n// notification, not 10. Any adapter can subscribe: Swagger, DevTools, WS, etc.\n\n/** A single container change event */\nexport interface ContainerChangeEvent {\n token: string\n event: 'registered' | 'resolved' | 'invalidated'\n kind?: ClassKind\n timestamp: number\n}\n\n/** Listener that receives batched change events */\nexport type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void\n\ninterface PersistentStore {\n factories: Array<{ token: any; factory: () => any; scope: Scope }>\n instances: Array<{ token: any; instance: any }>\n /** Resolved instances keyed by string name — survives class identity changes */\n resolvedInstances: Map<string, any>\n}\n\nfunction getPersistentStore(): PersistentStore {\n if (!(globalThis as any).__kickjs_persistent) {\n ;(globalThis as any).__kickjs_persistent = {\n factories: [],\n instances: [],\n resolvedInstances: new Map(),\n } satisfies PersistentStore\n }\n return (globalThis as any).__kickjs_persistent\n}\n\n/**\n * Inversion-of-Control (IoC) container that manages dependency registration,\n * resolution, and lifecycle. Implements the Singleton pattern so all parts of\n * the application share a single container instance.\n *\n * Supports constructor injection, property injection (@Autowired),\n * factory registrations, and lifecycle hooks (@PostConstruct).\n *\n * Persistent state (DB connections, Redis, etc.) is stored on globalThis so\n * it survives both Container.reset() and Vite module re-evaluation.\n */\nexport class Container {\n private static instance: Container\n private registrations = new Map<any, Registration>()\n private resolving = new Set<any>()\n\n // ── Reactive change tracking ──────────────────────────────────────\n private changeListeners = new Set<ContainerChangeListener>()\n private pendingChanges: ContainerChangeEvent[] = []\n private notifyTimer: ReturnType<typeof setTimeout> | null = null\n private static readonly DEBOUNCE_MS = 50\n\n /** Callback set by the decorators module to flush pending registrations */\n static _onReady: ((container: Container) => void) | null = null\n /** Callback invoked on reset so decorators can update their container reference */\n static _onReset: ((container: Container) => void) | null = null\n /**\n * Environment resolver for @Value decorator. Set by @forinda/kickjs-config\n * to return Zod-validated, type-coerced env values instead of raw process.env strings.\n */\n static _envResolver: ((key: string) => any) | null = null\n /**\n * Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http\n * to return the current request's AsyncLocalStorage store.\n * Returns { instances: Map, values: Map } or null if outside a request.\n */\n static _requestStoreProvider:\n | (() => { instances: Map<any, any>; values: Map<any, any> } | null)\n | null = null\n\n static getInstance(): Container {\n if (!Container.instance) {\n Container.instance = new Container()\n }\n // Flush any decorator registrations that queued before the container existed\n if (Container._onReady) {\n Container._onReady(Container.instance)\n Container._onReady = null\n }\n return Container.instance\n }\n\n /**\n * Resets the container by replacing the singleton with a fresh instance.\n * Persistent registrations (DB, Redis, etc.) are replayed from globalThis\n * so they survive both reset() and Vite module re-evaluation.\n */\n static reset(): void {\n Container.instance = new Container()\n // Notify decorators so they update their container reference\n Container._onReset?.(Container.instance)\n // Replay persistent registrations from globalThis store\n const store = getPersistentStore()\n for (const { token, factory, scope } of store.factories) {\n if (!Container.instance.has(token)) {\n // Check if we have a previously resolved instance for this token\n const name = tokenName(token)\n const existing = store.resolvedInstances.get(name)\n Container.instance.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existing, // Reuse resolved instance if available\n resolveCount: existing ? 1 : 0,\n postConstructStatus: existing ? 'completed' : 'skipped',\n }),\n )\n }\n }\n for (const { token, instance } of store.instances) {\n if (!Container.instance.has(token)) {\n Container.instance.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n }),\n )\n }\n }\n }\n\n /**\n * Create an isolated container instance (not the global singleton).\n * Useful for concurrent tests that must not share DI state.\n *\n * @example\n * ```ts\n * const container = Container.create()\n * container.register(UserService, UserService)\n * const svc = container.resolve(UserService)\n * ```\n */\n static create(): Container {\n return new Container()\n }\n\n /** Register a class constructor under the given token */\n register(token: any, target: Constructor, scope: Scope = Scope.SINGLETON): void {\n const kind = getClassMeta<ClassKind>(METADATA.CLASS_KIND, target, 'unknown')\n const dependencies = this.extractDependencies(target)\n const reg = createReg({ target, scope, kind, dependencies })\n this.registrations.set(token, reg)\n // Store a name-based fallback so HMR class re-creation (new identity)\n // can still resolve by the original class name.\n if (typeof token === 'function' && token.name) {\n this.registrations.set(`__hmr__${token.name}`, reg)\n }\n this.emit(tokenName(token), 'registered', kind)\n }\n\n /** Register a factory function under the given token */\n registerFactory(token: any, factory: () => any, scope: Scope = Scope.SINGLETON): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n // Check if we already have a resolved instance from a previous HMR cycle.\n // Only reuse if the factory hasn't changed (same reference). When a new\n // factory is provided (e.g. swapping implementations), clear the stale\n // instance so the new factory runs on next resolve.\n const existingEntry = store.factories.find((r) => tokenName(r.token) === name)\n const factoryUnchanged = existingEntry?.factory === factory\n const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : undefined\n\n // Clear stale resolved instance when factory changes\n if (!factoryUnchanged) {\n store.resolvedInstances.delete(name)\n }\n\n this.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existingInstance,\n resolveCount: existingInstance ? 1 : 0,\n postConstructStatus: existingInstance ? 'completed' : 'skipped',\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n const idx = store.factories.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.factories[idx] = { token, factory, scope }\n } else {\n store.factories.push({ token, factory, scope })\n }\n this.emit(name, 'registered', 'factory')\n }\n\n /** Register a pre-constructed singleton instance */\n registerInstance(token: any, instance: any): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n\n this.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n firstResolvedAt: Date.now(),\n lastResolvedAt: Date.now(),\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n store.resolvedInstances.set(name, instance)\n const idx = store.instances.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.instances[idx] = { token, instance }\n } else {\n store.instances.push({ token, instance })\n }\n this.emit(name, 'registered', 'instance')\n }\n\n /** Check if a binding exists for the given token */\n has(token: any): boolean {\n return this.registrations.has(token)\n }\n\n /** Return a snapshot of all registered tokens with their scope and instantiation status */\n getRegistrations(): Array<{\n token: string\n scope: string\n kind: ClassKind\n instantiated: boolean\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n }> {\n const entries: Array<ReturnType<Container['getRegistrations']>[number]> = []\n for (const [token, reg] of this.registrations) {\n entries.push({\n token: tokenName(token),\n scope: reg.scope,\n kind: reg.kind,\n // Singletons check cached instance; transients check resolveCount\n instantiated:\n reg.scope === Scope.SINGLETON ? reg.instance !== undefined : reg.resolveCount > 0,\n resolveCount: reg.resolveCount,\n lastResolvedAt: reg.lastResolvedAt,\n firstResolvedAt: reg.firstResolvedAt,\n resolveDurationMs: reg.resolveDurationMs,\n postConstructStatus: reg.postConstructStatus,\n dependencies: reg.dependencies,\n })\n }\n return entries\n }\n\n /** Resolve a dependency by its token */\n resolve<T = any>(token: any): T {\n let reg = this.registrations.get(token)\n // HMR fallback: when Vite re-evaluates a module, decorated classes get new\n // identity. Try resolving by class name if the primary token lookup fails.\n if (!reg && typeof token === 'function' && token.name) {\n reg = this.registrations.get(`__hmr__${token.name}`)\n }\n if (!reg) {\n throw new Error(`No binding found for: ${tokenName(token)}`)\n }\n\n if (reg.scope === Scope.SINGLETON && reg.instance !== undefined) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return reg.instance\n }\n\n // REQUEST scope: one instance per HTTP request, cached in AsyncLocalStorage\n if (reg.scope === Scope.REQUEST) {\n if (!Container._requestStoreProvider) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\": no request store provider configured. ` +\n `Ensure requestScopeMiddleware() is in your middleware pipeline.`,\n )\n }\n const store = Container._requestStoreProvider()\n if (!store) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\" outside an HTTP request context.`,\n )\n }\n // Check for pre-registered request values (user, tenant, etc.)\n if (store.values.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.values.get(token) as T\n }\n // Check per-request instance cache\n if (store.instances.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.instances.get(token) as T\n }\n // Create instance and cache for this request only\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n store.instances.set(token, instance)\n return instance as T\n }\n\n if (reg.factory) {\n const start = performance.now()\n const instance = reg.factory()\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n // Persist resolved factory instances so they survive module re-evaluation\n getPersistentStore().resolvedInstances.set(tokenName(token), instance)\n }\n return instance\n }\n\n if (this.resolving.has(token)) {\n const chain = [...this.resolving].map(tokenName)\n chain.push(tokenName(token))\n throw new Error(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n this.resolving.add(token)\n\n try {\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n }\n return instance\n } finally {\n this.resolving.delete(token)\n }\n }\n\n /** Lifecycle hook called during Application.setup() after module registration */\n bootstrap(): void {\n // Reserved for future use — adapters and modules register via\n // container.register(), registerFactory(), and registerInstance().\n }\n\n // ── Reactive Change API ─────────────────────────────────────────────\n\n /**\n * Subscribe to container changes. Returns an unsubscribe function.\n *\n * Changes are batched (50ms debounce) so bulk operations like\n * `kick g module` creating 10+ files emit ONE batch, not 10 events.\n *\n * Any adapter can subscribe:\n * - SwaggerAdapter: re-build spec when controllers change\n * - DevToolsAdapter: push SSE events to dashboard\n * - WsAdapter: re-discover namespaces when controllers change\n * - OtelAdapter: emit tracing spans for DI resolution\n * - Custom user adapters\n *\n * @example\n * ```ts\n * const unsub = container.onChange((changes) => {\n * for (const c of changes) {\n * console.log(`${c.event}: ${c.token} (${c.kind})`)\n * }\n * })\n * // later:\n * unsub()\n * ```\n */\n onChange(callback: ContainerChangeListener): () => void {\n this.changeListeners.add(callback)\n return () => this.changeListeners.delete(callback)\n }\n\n /**\n * Invalidate a specific registration. Clears the cached instance so the\n * next resolve() creates a fresh one. Also invalidates dependents\n * (anything that injected this token) by walking the dependency graph.\n *\n * Called by the Vite HMR plugin when a module file changes.\n * Skips persistent registrations (DB connections, etc.).\n */\n invalidate(token: any): void {\n const name = tokenName(token)\n // Try both the token itself and the HMR fallback name\n const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`)\n if (!reg) return\n\n // Don't invalidate persistent registrations (DB, Redis, etc.)\n const store = getPersistentStore()\n if (store.resolvedInstances.has(name)) return\n\n // Clear cached instance — next resolve() will re-create\n reg.instance = undefined\n reg.resolveCount = 0\n reg.postConstructStatus = 'skipped'\n this.emit(name, 'invalidated', reg.kind)\n\n // Walk dependency graph — invalidate anything that injected this token\n for (const [depToken, depReg] of this.registrations) {\n if (depReg.dependencies.includes(name)) {\n this.invalidate(depToken)\n }\n }\n }\n\n /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */\n private emit(token: string, event: ContainerChangeEvent['event'], kind?: ClassKind): void {\n this.pendingChanges.push({ token, event, kind, timestamp: Date.now() })\n\n if (this.notifyTimer) clearTimeout(this.notifyTimer)\n this.notifyTimer = setTimeout(() => {\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }, Container.DEBOUNCE_MS)\n }\n\n /** Flush pending change events immediately (useful in tests) */\n flushChanges(): void {\n if (this.notifyTimer) {\n clearTimeout(this.notifyTimer)\n this.notifyTimer = null\n }\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }\n\n private createInstance(reg: Registration): any {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, reg.target, [])\n\n const args = paramTypes.map((paramType, index) => {\n // Check for @Inject token override on constructor parameter\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, reg.target)\n const token = injectTokens[index] || paramType\n // Scope validation: SINGLETON cannot inject REQUEST-scoped dependencies\n if (reg.scope === Scope.SINGLETON) {\n const depReg = this.registrations.get(token)\n if (depReg && depReg.scope === Scope.REQUEST) {\n throw new Error(\n `Cannot inject REQUEST-scoped \"${tokenName(token)}\" into SINGLETON \"${tokenName(reg.target)}\". ` +\n `Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`,\n )\n }\n }\n return this.resolve(token)\n })\n\n const instance = new reg.target(...args)\n\n // Property injection via @Autowired\n this.injectProperties(instance, reg.target)\n\n // @PostConstruct lifecycle hook\n const postConstruct = getClassMetaOrUndefined<string | symbol>(\n METADATA.POST_CONSTRUCT,\n reg.target.prototype,\n )\n if (postConstruct && typeof instance[postConstruct] === 'function') {\n try {\n const result = instance[postConstruct]()\n if (result && typeof result.then === 'function') {\n reg.postConstructStatus = 'pending'\n ;(result as Promise<void>)\n .then(() => {\n reg.postConstructStatus = 'completed'\n })\n .catch(() => {\n reg.postConstructStatus = 'failed'\n })\n log.warn(\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise ` +\n `but the container is synchronous. The async operation will not be awaited.`,\n )\n } else {\n reg.postConstructStatus = 'completed'\n }\n } catch (err) {\n reg.postConstructStatus = 'failed'\n log.error(\n err,\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`,\n )\n }\n }\n\n return instance\n }\n\n /** Extract dependency token names from constructor metadata */\n private extractDependencies(target: Constructor): string[] {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, target, [])\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, target)\n return paramTypes.map((type, index) => {\n const token = injectTokens[index] || type\n return tokenName(token)\n })\n }\n\n private injectProperties(instance: any, target: Constructor): void {\n // @Autowired — lazy DI property injection\n const autowiredProps = getMetaMap<string, any>(METADATA.AUTOWIRED, target.prototype)\n\n for (const [prop, token] of autowiredProps) {\n const resolvedToken =\n token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop)\n if (resolvedToken) {\n Object.defineProperty(instance, prop, {\n get: () => this.resolve(resolvedToken),\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n // @Value — lazy environment variable injection\n const valueProps = getMetaMap<string, { envKey: string; defaultValue?: any }>(\n METADATA.VALUE,\n target.prototype,\n )\n\n for (const [prop, config] of valueProps) {\n Object.defineProperty(instance, prop, {\n get() {\n // Use the registered env resolver if available (set by @forinda/kickjs-config)\n // This returns Zod-validated, type-coerced values (e.g. PORT as number)\n if (Container._envResolver) {\n const val = Container._envResolver(config.envKey)\n if (val !== undefined) return val\n }\n\n // Fallback to raw process.env for apps not using @forinda/kickjs-config\n const val = process.env[config.envKey]\n if (val !== undefined) return val\n if (config.defaultValue !== undefined) return config.defaultValue\n throw new Error(\n `@Value('${config.envKey}'): Environment variable \"${config.envKey}\" is not set and no default was provided.`,\n )\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAM,MAAM,aAAa,YAAY;;AAmBrC,SAAS,UACP,QACc;AACd,QAAO;EACL,MAAM;EACN,cAAc;EACd,qBAAqB;EACrB,cAAc,EAAE;EAChB,GAAG;EACJ;;;AAIH,SAAgB,UAAU,OAAoB;AAC5C,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,UAAU;AACtD,QAAO,OAAO,QAAQ,OAAO,MAAM;;AAmCrC,SAAS,qBAAsC;AAC7C,KAAI,CAAE,WAAmB,oBACrB,YAAmB,sBAAsB;EACzC,WAAW,EAAE;EACb,WAAW,EAAE;EACb,mCAAmB,IAAI,KAAK;EAC7B;AAEH,QAAQ,WAAmB;;;;;;;;;;;;;AAc7B,IAAa,YAAb,MAAa,UAAU;CACrB,OAAe;CACf,gCAAwB,IAAI,KAAwB;CACpD,4BAAoB,IAAI,KAAU;CAGlC,kCAA0B,IAAI,KAA8B;CAC5D,iBAAiD,EAAE;CACnD,cAA4D;CAC5D,OAAwB,cAAc;;CAGtC,OAAO,WAAoD;;CAE3D,OAAO,WAAoD;;;;;CAK3D,OAAO,eAA8C;;;;;;CAMrD,OAAO,wBAEI;CAEX,OAAO,cAAyB;AAC9B,MAAI,CAAC,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