@forinda/kickjs 10.3.0 → 10.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-BZ1WzN1z.d.mts +2354 -0
- package/dist/adapter-BZ1WzN1z.d.mts.map +1 -0
- package/dist/{app-module-Ftz6m7SO.d.mts → app-module-Cuu-Ma_E.d.mts} +5 -4
- package/dist/app-module-Cuu-Ma_E.d.mts.map +1 -0
- package/dist/{application-B2e5XYHm.mjs → application-Bs30gJF1.mjs} +4 -4
- package/dist/application-Bs30gJF1.mjs.map +1 -0
- package/dist/application-D5Iiy7rt.d.mts +1996 -0
- package/dist/application-D5Iiy7rt.d.mts.map +1 -0
- package/dist/bootstrap-B_sGJNSz.mjs +12 -0
- package/dist/{bootstrap-BmALF-1Y.mjs.map → bootstrap-B_sGJNSz.mjs.map} +1 -1
- package/dist/{bounded-counters-aA3iI_Ei.mjs → bounded-counters-DS-IbDW9.mjs} +2 -2
- package/dist/{bounded-counters-aA3iI_Ei.mjs.map → bounded-counters-DS-IbDW9.mjs.map} +1 -1
- package/dist/{client-ip-D2dsx8RG.mjs → client-ip-BLkoQTIR.mjs} +2 -2
- package/dist/{client-ip-D2dsx8RG.mjs.map → client-ip-BLkoQTIR.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-B77LTW_E.mjs → config-B6EeAw4P.mjs} +3 -3
- package/dist/{config-B77LTW_E.mjs.map → config-B6EeAw4P.mjs.map} +1 -1
- package/dist/container-4iJdDkRH.d.mts +3 -0
- package/dist/context-CRJzl_Mj.mjs +12 -0
- package/dist/context-CRJzl_Mj.mjs.map +1 -0
- package/dist/{context-errors-CPqYYhl0.mjs → context-errors-CR5NCXfl.mjs} +2 -2
- package/dist/{context-errors-CPqYYhl0.mjs.map → context-errors-CR5NCXfl.mjs.map} +1 -1
- package/dist/{contributor-runner-Cl5yZZy1.mjs → contributor-runner--ofCRZ0d.mjs} +3 -3
- package/dist/{contributor-runner-Cl5yZZy1.mjs.map → contributor-runner--ofCRZ0d.mjs.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.mjs +1 -1
- package/dist/core/container.d.mts +2 -2
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +2 -2
- package/dist/core/interfaces.mjs +2 -2
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +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.mjs +1 -1
- package/dist/core-CsMDdzNE.mjs +12 -0
- package/dist/{core-D1AV-Tvd.mjs.map → core-CsMDdzNE.mjs.map} +1 -1
- package/dist/{csrf-Cy1meSpf.d.mts → csrf-BDAZK2mm.d.mts} +2 -2
- package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-BDAZK2mm.d.mts.map} +1 -1
- package/dist/decorate-CLeX6hbL.mjs +13 -0
- package/dist/{decorate-BiXL-9e9.mjs.map → decorate-CLeX6hbL.mjs.map} +1 -1
- package/dist/{decorators-DaQUNXOn.d.mts → decorators-Dvy0JZ5L.d.mts} +8 -200
- package/dist/decorators-Dvy0JZ5L.d.mts.map +1 -0
- package/dist/{define-adapter-D22SDe0U.mjs → define-adapter-RbKRSG3i.mjs} +2 -2
- package/dist/{define-adapter-D22SDe0U.mjs.map → define-adapter-RbKRSG3i.mjs.map} +1 -1
- package/dist/di-hooks-CiNaIu12.mjs +132 -0
- package/dist/di-hooks-CiNaIu12.mjs.map +1 -0
- package/dist/disposables-DYTkgNiG.mjs +11 -0
- package/dist/error-handler-CbP7hKdJ.d.mts +63 -0
- package/dist/error-handler-CbP7hKdJ.d.mts.map +1 -0
- package/dist/{handler-gW_h2miq.mjs → handler-Cw4mr3ls.mjs} +3 -3
- package/dist/{handler-gW_h2miq.mjs.map → handler-Cw4mr3ls.mjs.map} +1 -1
- package/dist/{host-D__uZPyz.mjs → host-H7CIkHNB.mjs} +2 -2
- package/dist/{host-D__uZPyz.mjs.map → host-H7CIkHNB.mjs.map} +1 -1
- package/dist/http/application.d.mts +2 -2
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +3 -2
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.d.mts +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/{index-CuiWSnZL.d.mts → index-B4aOLoId.d.mts} +4 -4
- package/dist/{index-CuiWSnZL.d.mts.map → index-B4aOLoId.d.mts.map} +1 -1
- package/dist/{index-BfT5KZ-M.d.mts → index-Blgka75E.d.mts} +63 -4
- package/dist/index-Blgka75E.d.mts.map +1 -0
- package/dist/index.d.mts +17 -11
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/interfaces-C6LHcYsg.d.mts +34 -0
- package/dist/interfaces-C6LHcYsg.d.mts.map +1 -0
- package/dist/is-production-BTroGhp5.mjs +12 -0
- package/dist/is-production-BTroGhp5.mjs.map +1 -0
- package/dist/jobs-xqoMmdr4.mjs +12 -0
- package/dist/{jobs-s4__kZLr.mjs.map → jobs-xqoMmdr4.mjs.map} +1 -1
- package/dist/{kv-stores-Cjel_Dkc.mjs → kv-stores-0-6blGzh.mjs} +3 -3
- package/dist/{kv-stores-Cjel_Dkc.mjs.map → kv-stores-0-6blGzh.mjs.map} +1 -1
- package/dist/kv-stores-DXFBEYYu.d.mts +390 -0
- package/dist/kv-stores-DXFBEYYu.d.mts.map +1 -0
- package/dist/{lazy-serve-static-w94Xs3wQ.mjs → lazy-serve-static-D94xvah5.mjs} +2 -2
- package/dist/{lazy-serve-static-w94Xs3wQ.mjs.map → lazy-serve-static-D94xvah5.mjs.map} +1 -1
- package/dist/metadata-Bm65Y-5O.mjs +11 -0
- package/dist/{observers-boPE9XGi.mjs → observers-BAXkwMx0.mjs} +2 -2
- package/dist/{observers-boPE9XGi.mjs.map → observers-BAXkwMx0.mjs.map} +1 -1
- package/dist/query-CGyw7vNi.mjs +12 -0
- package/dist/query-CGyw7vNi.mjs.map +1 -0
- package/dist/{reply-CYY_CzRf.mjs → reply-tlUaowib.mjs} +3 -3
- package/dist/{reply-CYY_CzRf.mjs.map → reply-tlUaowib.mjs.map} +1 -1
- package/dist/{respond-Dc18G0X7.mjs → respond-BOlh-baJ.mjs} +2 -2
- package/dist/{respond-Dc18G0X7.mjs.map → respond-BOlh-baJ.mjs.map} +1 -1
- package/dist/{route-flag-BOQZs2Wn.mjs → route-flag-BPSq2JCs.mjs} +3 -3
- package/dist/{route-flag-BOQZs2Wn.mjs.map → route-flag-BPSq2JCs.mjs.map} +1 -1
- package/dist/{route-policy-B8c6QfiU.mjs → route-policy-DDszB6dQ.mjs} +2 -2
- package/dist/{route-policy-B8c6QfiU.mjs.map → route-policy-DDszB6dQ.mjs.map} +1 -1
- package/dist/router-builder-BewIsj7V.d.mts +56 -0
- package/dist/router-builder-BewIsj7V.d.mts.map +1 -0
- package/dist/router-builder-DoaDAmK8.mjs +12 -0
- package/dist/{router-builder-DoWOIGmG.mjs.map → router-builder-DoaDAmK8.mjs.map} +1 -1
- package/dist/{settings-C8VKewNS.d.mts → settings-BnE75hnr.d.mts} +2 -2
- package/dist/{settings-C8VKewNS.d.mts.map → settings-BnE75hnr.d.mts.map} +1 -1
- package/dist/settings-CRkMOwcz.mjs +14 -0
- package/dist/{settings-DcytOCC6.mjs.map → settings-CRkMOwcz.mjs.map} +1 -1
- package/dist/token-2CJq89za.mjs +11 -0
- package/dist/token-D6jfTQLA.d.mts +3 -0
- package/dist/upload-DkT2p1gd.d.mts +104 -0
- package/dist/upload-DkT2p1gd.d.mts.map +1 -0
- package/dist/{upload-config-CzxbJALL.mjs → upload-config-Be7w0Dfx.mjs} +2 -2
- package/dist/{upload-config-CzxbJALL.mjs.map → upload-config-Be7w0Dfx.mjs.map} +1 -1
- package/dist/url-for-EQsmb3yi.mjs +12 -0
- package/dist/url-for-EQsmb3yi.mjs.map +1 -0
- package/dist/web-crypto-G-m6c6w2.mjs +12 -0
- package/dist/web-crypto-G-m6c6w2.mjs.map +1 -0
- package/dist/web.d.mts +6 -5
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +2 -1
- package/dist/adapter-BYdxuKiM.d.mts +0 -4916
- package/dist/adapter-BYdxuKiM.d.mts.map +0 -1
- package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
- package/dist/application-B2e5XYHm.mjs.map +0 -1
- package/dist/bootstrap-BmALF-1Y.mjs +0 -12
- package/dist/container-Dpvd66Yt.d.mts +0 -298
- package/dist/container-Dpvd66Yt.d.mts.map +0 -1
- package/dist/container-mvaAYThX.mjs +0 -132
- package/dist/container-mvaAYThX.mjs.map +0 -1
- package/dist/context-GbQnJB-L.mjs +0 -12
- package/dist/context-GbQnJB-L.mjs.map +0 -1
- package/dist/core-D1AV-Tvd.mjs +0 -12
- package/dist/csrf-D3prC4FK.mjs +0 -12
- package/dist/csrf-D3prC4FK.mjs.map +0 -1
- package/dist/decorate-BiXL-9e9.mjs +0 -13
- package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
- package/dist/disposables-CJD_gWlA.mjs +0 -12
- package/dist/disposables-CJD_gWlA.mjs.map +0 -1
- package/dist/index-BfT5KZ-M.d.mts.map +0 -1
- package/dist/interfaces-C1hCSoLD.d.mts +0 -75
- package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
- package/dist/is-production-Dbm13WNL.mjs +0 -12
- package/dist/is-production-Dbm13WNL.mjs.map +0 -1
- package/dist/jobs-s4__kZLr.mjs +0 -12
- package/dist/metadata-C2GK_17k.mjs +0 -12
- package/dist/metadata-C2GK_17k.mjs.map +0 -1
- package/dist/query-DjTeF1d4.mjs +0 -12
- package/dist/query-DjTeF1d4.mjs.map +0 -1
- package/dist/router-builder-DoWOIGmG.mjs +0 -12
- package/dist/settings-DcytOCC6.mjs +0 -14
- package/dist/url-for-DGSrVfdD.mjs +0 -12
- package/dist/url-for-DGSrVfdD.mjs.map +0 -1
|
@@ -1,298 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-C1hCSoLD.mjs";
|
|
3
|
-
import "reflect-metadata";
|
|
4
|
-
//#region src/core/token.d.ts
|
|
5
|
-
/**
|
|
6
|
-
* Collision-safe injection tokens with phantom type parameters.
|
|
7
|
-
*
|
|
8
|
-
* `createToken<T>(name)` is the recommended way to declare any DI token
|
|
9
|
-
* that isn't a class. Each call returns a unique frozen object — even if
|
|
10
|
-
* two files write `createToken<X>('Logger')`, they produce two distinct
|
|
11
|
-
* references that the container treats as different tokens. Collisions
|
|
12
|
-
* become impossible by construction, not by convention.
|
|
13
|
-
*
|
|
14
|
-
* The phantom type parameter `T` lets `container.resolve(token)` infer
|
|
15
|
-
* the correct return type without any codegen.
|
|
16
|
-
*
|
|
17
|
-
* ## Hardening layers
|
|
18
|
-
*
|
|
19
|
-
* KickJS has four DI token kinds, listed from safest to riskiest:
|
|
20
|
-
*
|
|
21
|
-
* 1. **Class identity** — `container.resolve(UserService)`. Reference
|
|
22
|
-
* equality, never collides. Type-safe via `Constructor<T>` overload.
|
|
23
|
-
* 2. **`createToken<T>(name)`** — frozen object identity, never collides.
|
|
24
|
-
* Type-safe via the `InjectionToken<T>` overload.
|
|
25
|
-
* 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`
|
|
26
|
-
* is interned and CAN collide. Discouraged.
|
|
27
|
-
* 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.
|
|
28
|
-
* Reserved for legacy code and runtime-computed token names.
|
|
29
|
-
*
|
|
30
|
-
* Prefer (1) and (2). Use (4) only when you have to.
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```ts
|
|
34
|
-
* // src/tokens.ts
|
|
35
|
-
* export const DATABASE_URL = createToken<string>('config.database.url')
|
|
36
|
-
* export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')
|
|
37
|
-
*
|
|
38
|
-
* // bootstrap
|
|
39
|
-
* container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)
|
|
40
|
-
*
|
|
41
|
-
* // anywhere else
|
|
42
|
-
* const url = container.resolve(DATABASE_URL) // typed as `string`
|
|
43
|
-
* ```
|
|
44
|
-
*
|
|
45
|
-
* @module @forinda/kickjs/core/token
|
|
46
|
-
*/
|
|
47
|
-
/**
|
|
48
|
-
* Symbol marker stamped on every InjectionToken so the container can
|
|
49
|
-
* detect them at runtime regardless of which package created them.
|
|
50
|
-
*
|
|
51
|
-
* Uses `Symbol.for()` so cross-package isolation (different copies of
|
|
52
|
-
* `@forinda/kickjs` loaded under different module identities) still
|
|
53
|
-
* shares the same marker.
|
|
54
|
-
*/
|
|
55
|
-
declare const INJECTION_TOKEN: unique symbol;
|
|
56
|
-
/**
|
|
57
|
-
* A type-safe DI token. Each `createToken()` call returns a unique frozen
|
|
58
|
-
* object identified by reference, not by the `name` string. Two
|
|
59
|
-
* `createToken<X>('foo')` calls in different files produce two distinct
|
|
60
|
-
* tokens that the container treats independently.
|
|
61
|
-
*
|
|
62
|
-
* The phantom `_type` parameter is never assigned at runtime — it exists
|
|
63
|
-
* solely to thread the type through `container.resolve(token)`.
|
|
64
|
-
*/
|
|
65
|
-
interface InjectionToken<T> {
|
|
66
|
-
readonly [INJECTION_TOKEN]: true;
|
|
67
|
-
/** Descriptive name used in error messages, logs, and devtools */
|
|
68
|
-
readonly name: string;
|
|
69
|
-
/** Phantom — never assigned at runtime */
|
|
70
|
-
readonly _type?: T;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Create a collision-safe injection token.
|
|
74
|
-
*
|
|
75
|
-
* The returned token is a frozen object identified by reference, not by
|
|
76
|
-
* the `name` string. The `name` is used only for error messages, logs,
|
|
77
|
-
* and debugging.
|
|
78
|
-
*/
|
|
79
|
-
declare function createToken<T>(name: string): InjectionToken<T>;
|
|
80
|
-
/** Type guard — returns `true` if `value` is an InjectionToken */
|
|
81
|
-
declare function isInjectionToken(value: unknown): value is InjectionToken<unknown>;
|
|
82
|
-
//#endregion
|
|
83
|
-
//#region src/core/container.d.ts
|
|
84
|
-
/** Format a token for display in error messages */
|
|
85
|
-
declare function tokenName(token: any): string;
|
|
86
|
-
/** A single container change event */
|
|
87
|
-
interface ContainerChangeEvent {
|
|
88
|
-
token: string;
|
|
89
|
-
event: 'registered' | 'resolved' | 'invalidated';
|
|
90
|
-
kind?: ClassKind;
|
|
91
|
-
timestamp: number;
|
|
92
|
-
}
|
|
93
|
-
/** Listener that receives batched change events */
|
|
94
|
-
type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void;
|
|
95
|
-
/**
|
|
96
|
-
* Type-safe registry of string DI tokens. Augmented by `kick typegen` —
|
|
97
|
-
* the generated `.kickjs/types/registry.d.ts` adds entries like:
|
|
98
|
-
*
|
|
99
|
-
* ```ts
|
|
100
|
-
* declare module '@forinda/kickjs' {
|
|
101
|
-
* interface KickJsRegistry {
|
|
102
|
-
* UserService: import('../../src/modules/users/user.service').UserService
|
|
103
|
-
* }
|
|
104
|
-
* }
|
|
105
|
-
* ```
|
|
106
|
-
*
|
|
107
|
-
* Once typegen has run, `container.resolve('UserService')` returns the
|
|
108
|
-
* correct type instead of `any`. Class-token resolution
|
|
109
|
-
* (`container.resolve(UserService)`) is already type-safe via the
|
|
110
|
-
* `Constructor<T>` overload and does not need typegen.
|
|
111
|
-
*/
|
|
112
|
-
interface KickJsRegistry {}
|
|
113
|
-
/**
|
|
114
|
-
* Inversion-of-Control (IoC) container that manages dependency registration,
|
|
115
|
-
* resolution, and lifecycle. Implements the Singleton pattern so all parts of
|
|
116
|
-
* the application share a single container instance.
|
|
117
|
-
*
|
|
118
|
-
* Supports constructor injection, property injection (@Autowired),
|
|
119
|
-
* factory registrations, and lifecycle hooks (@PostConstruct).
|
|
120
|
-
*
|
|
121
|
-
* Persistent state (DB connections, Redis, etc.) is stored on globalThis so
|
|
122
|
-
* it survives both Container.reset() and Vite module re-evaluation.
|
|
123
|
-
*/
|
|
124
|
-
declare class Container {
|
|
125
|
-
private static instance;
|
|
126
|
-
private registrations;
|
|
127
|
-
private resolving;
|
|
128
|
-
private changeListeners;
|
|
129
|
-
private pendingChanges;
|
|
130
|
-
private notifyTimer;
|
|
131
|
-
private static readonly DEBOUNCE_MS;
|
|
132
|
-
/** Callback set by the decorators module to flush pending registrations */
|
|
133
|
-
static _onReady: ((container: Container) => void) | null;
|
|
134
|
-
/** Callback invoked on reset so decorators can update their container reference */
|
|
135
|
-
static _onReset: ((container: Container) => void) | null;
|
|
136
|
-
/**
|
|
137
|
-
* Seeds a NEWLY CREATED container with the decorator registrations, without
|
|
138
|
-
* adopting it as the global one. `_onReset` does both; an isolated container
|
|
139
|
-
* must only have the first half, or it would capture every subsequent
|
|
140
|
-
* decorator registration in the process.
|
|
141
|
-
*/
|
|
142
|
-
static _onCreate: ((container: Container) => void) | null;
|
|
143
|
-
/**
|
|
144
|
-
* Environment resolver for @Value decorator. Set by the unified
|
|
145
|
-
* `@forinda/kickjs` config layer to return Zod-validated, type-coerced
|
|
146
|
-
* env values instead of raw process.env strings.
|
|
147
|
-
*/
|
|
148
|
-
static _envResolver: ((key: string) => any) | null;
|
|
149
|
-
/**
|
|
150
|
-
* Request store provider for REQUEST-scoped DI. Set by the HTTP layer
|
|
151
|
-
* inside `@forinda/kickjs` to return the current request's
|
|
152
|
-
* AsyncLocalStorage store. Returns { instances: Map, values: Map } or
|
|
153
|
-
* null if outside a request.
|
|
154
|
-
*/
|
|
155
|
-
/**
|
|
156
|
-
* Whether this container is the global singleton.
|
|
157
|
-
*
|
|
158
|
-
* The persistent store exists to carry the GLOBAL container's registrations
|
|
159
|
-
* across HMR and module re-evaluation. An isolated container is per-test and
|
|
160
|
-
* must neither write to it — a `registerInstance` override was replayed into
|
|
161
|
-
* every later `Container.reset()` — nor read from it, which would pull global
|
|
162
|
-
* state into a container created to be free of it.
|
|
163
|
-
*/
|
|
164
|
-
private isGlobal;
|
|
165
|
-
static _requestStoreProvider: (() => {
|
|
166
|
-
instances: Map<any, any>;
|
|
167
|
-
values: Map<any, any>;
|
|
168
|
-
} | null) | null;
|
|
169
|
-
static getInstance(): Container;
|
|
170
|
-
/**
|
|
171
|
-
* Resets the container by replacing the singleton with a fresh instance.
|
|
172
|
-
* Persistent registrations (DB, Redis, etc.) are replayed from globalThis
|
|
173
|
-
* so they survive both reset() and Vite module re-evaluation.
|
|
174
|
-
*/
|
|
175
|
-
static reset(): void;
|
|
176
|
-
/**
|
|
177
|
-
* Create an isolated container instance (not the global singleton).
|
|
178
|
-
* Useful for concurrent tests that must not share DI state.
|
|
179
|
-
*
|
|
180
|
-
* @example
|
|
181
|
-
* ```ts
|
|
182
|
-
* const container = Container.create()
|
|
183
|
-
* container.register(UserService, UserService)
|
|
184
|
-
* const svc = container.resolve(UserService)
|
|
185
|
-
* ```
|
|
186
|
-
*/
|
|
187
|
-
static create(): Container;
|
|
188
|
-
/** Register a class constructor under the given token */
|
|
189
|
-
register(token: any, target: Constructor, scope?: Scope): void;
|
|
190
|
-
/** Register a factory function under the given token */
|
|
191
|
-
registerFactory(token: any, factory: () => any, scope?: Scope): void;
|
|
192
|
-
/** Register a pre-constructed singleton instance */
|
|
193
|
-
registerInstance(token: any, instance: any): void;
|
|
194
|
-
/** Check if a binding exists for the given token */
|
|
195
|
-
has(token: any): boolean;
|
|
196
|
-
/** Return a snapshot of all registered tokens with their scope and instantiation status */
|
|
197
|
-
getRegistrations(): Array<{
|
|
198
|
-
token: string;
|
|
199
|
-
scope: string;
|
|
200
|
-
kind: ClassKind;
|
|
201
|
-
instantiated: boolean;
|
|
202
|
-
resolveCount: number;
|
|
203
|
-
lastResolvedAt?: number;
|
|
204
|
-
firstResolvedAt?: number;
|
|
205
|
-
resolveDurationMs?: number;
|
|
206
|
-
postConstructStatus: PostConstructStatus;
|
|
207
|
-
dependencies: string[];
|
|
208
|
-
}>;
|
|
209
|
-
/**
|
|
210
|
-
* Resolve a dependency by its token.
|
|
211
|
-
*
|
|
212
|
-
* Four overloads, in order of preference:
|
|
213
|
-
* - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.
|
|
214
|
-
* Collision-safe by construction; no codegen required.
|
|
215
|
-
* - **Class constructor** → returns an instance of that class. Always
|
|
216
|
-
* type-safe; no codegen required.
|
|
217
|
-
* - **String token in `KickJsRegistry`** (populated by `kick typegen`) →
|
|
218
|
-
* returns the augmented type.
|
|
219
|
-
* - **Anything else** → returns `any`. Use this only for legacy code or
|
|
220
|
-
* string tokens that haven't been registered with typegen yet.
|
|
221
|
-
*/
|
|
222
|
-
resolve<T>(token: InjectionToken<T>): T;
|
|
223
|
-
resolve<T>(token: Constructor<T>): T;
|
|
224
|
-
resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K];
|
|
225
|
-
resolve<T = any>(token: any): T;
|
|
226
|
-
/** Lifecycle hook called during Application.setup() after module registration */
|
|
227
|
-
bootstrap(): void;
|
|
228
|
-
/**
|
|
229
|
-
* Subscribe to container changes. Returns an unsubscribe function.
|
|
230
|
-
*
|
|
231
|
-
* Changes are batched (50ms debounce) so bulk operations like
|
|
232
|
-
* `kick g module` creating 10+ files emit ONE batch, not 10 events.
|
|
233
|
-
*
|
|
234
|
-
* Any adapter can subscribe:
|
|
235
|
-
* - SwaggerAdapter: re-build spec when controllers change
|
|
236
|
-
* - DevToolsAdapter: push SSE events to dashboard
|
|
237
|
-
* - WsAdapter: re-discover namespaces when controllers change
|
|
238
|
-
* - OtelAdapter: emit tracing spans for DI resolution
|
|
239
|
-
* - Custom user adapters
|
|
240
|
-
*
|
|
241
|
-
* @example
|
|
242
|
-
* ```ts
|
|
243
|
-
* const unsub = container.onChange((changes) => {
|
|
244
|
-
* for (const c of changes) {
|
|
245
|
-
* console.log(`${c.event}: ${c.token} (${c.kind})`)
|
|
246
|
-
* }
|
|
247
|
-
* })
|
|
248
|
-
* // later:
|
|
249
|
-
* unsub()
|
|
250
|
-
* ```
|
|
251
|
-
*/
|
|
252
|
-
onChange(callback: ContainerChangeListener): () => void;
|
|
253
|
-
/**
|
|
254
|
-
* Invalidate a specific registration. Clears the cached instance so the
|
|
255
|
-
* next resolve() creates a fresh one. Also invalidates dependents
|
|
256
|
-
* (anything that injected this token) by walking the dependency graph.
|
|
257
|
-
*
|
|
258
|
-
* Called by the Vite HMR plugin when a module file changes.
|
|
259
|
-
* Skips persistent registrations (DB connections, etc.).
|
|
260
|
-
*/
|
|
261
|
-
invalidate(token: any): void;
|
|
262
|
-
/**
|
|
263
|
-
* Batch-emit a change event (debounced, flushed after 50ms of quiet).
|
|
264
|
-
* Takes the RAW token — `tokenName()` is only computed after the
|
|
265
|
-
* zero-listener guard, so the hot cached-singleton resolve path never pays
|
|
266
|
-
* the name derivation when nobody is watching (the production default).
|
|
267
|
-
*/
|
|
268
|
-
private emit;
|
|
269
|
-
/** Flush pending change events immediately (useful in tests) */
|
|
270
|
-
flushChanges(): void;
|
|
271
|
-
/**
|
|
272
|
-
* Build the one-time instantiation plan for a registration. Runs on the
|
|
273
|
-
* FIRST createInstance for the class — the metadata it reads is immutable
|
|
274
|
-
* after class definition, so every later create (REQUEST scope: every
|
|
275
|
-
* request) skips all Reflect reads and re-derivation.
|
|
276
|
-
*
|
|
277
|
-
* Scope validation (SINGLETON must not ctor-inject REQUEST) lives here
|
|
278
|
-
* too: it's a static property of the (parent, dep) registration pair, so
|
|
279
|
-
* checking it once at plan build is equivalent to the old per-create loop.
|
|
280
|
-
*/
|
|
281
|
-
private buildPlan;
|
|
282
|
-
private createInstance;
|
|
283
|
-
/**
|
|
284
|
-
* Extract every dependency token name a class declares — both
|
|
285
|
-
* constructor params (`@Inject` + emitted `design:paramtypes`) and
|
|
286
|
-
* `@Autowired` properties (read lazily at injection time, but
|
|
287
|
-
* captured here so devtools surfaces a complete dependency graph).
|
|
288
|
-
*
|
|
289
|
-
* Without the property branch, classes that rely entirely on
|
|
290
|
-
* `@Autowired` show `dependencies: []` in the introspection panel
|
|
291
|
-
* even though they have real DI deps — see /_debug topology.
|
|
292
|
-
*/
|
|
293
|
-
private extractDependencies;
|
|
294
|
-
private injectProperties;
|
|
295
|
-
}
|
|
296
|
-
//#endregion
|
|
297
|
-
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 };
|
|
298
|
-
//# sourceMappingURL=container-Dpvd66Yt.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"container-Dpvd66Yt.d.mts","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmDa;;;;;;;;;;UAWI,eAAe;YACpB;;WAED;;WAEA,QAAQ;;;;;;;;;iBAUH,YAAY,GAAG,eAAe,eAAe;;iBAQ7C,iBAAiB,iBAAiB,SAAS;;;;iBCL3C,UAAU;;UAqBT;EACf;EACA;EACA,OAAO;EACP;;;KAIU,2BAA2B,SAAS;;;;;;;;;;;;;;;;;;UAmB/B;;;;;;;;;;;;cA+BJ;iBACI;UACP;UACA;UAGA;UACA;UACA;0BACgB;;SAGjB,YAAY,WAAW;;SAEvB,YAAY,WAAW;;;;;;;SAQvB,aAAa,WAAW;;;;;;SAMxB,gBAAgB;;;;;;;;;;;;;;;;UAgBf;SAED;IACM,WAAW;IAAe,QAAQ;;SAGxC,eAAe;;;;;;SAkBf;;;;;;;;;;;;SAsDA,UAAU;;EAYjB,SAAS,YAAY,QAAQ,aAAa,QAAO;;EAcjD,gBAAgB,YAAY,oBAAoB,QAAO;;EAiDvD,iBAAiB,YAAY;;EAiC7B,IAAI;;EAKJ,oBAAoB;IAClB;IACA;IACA,MAAM;IACN;IACA;IACA;IACA;IACA;IACA,qBAAqB;IACrB;;;;;;;;;;;;;;;EAmCF,QAAQ,GAAG,OAAO,eAAe,KAAK;EACtC,QAAQ,GAAG,OAAO,YAAY,KAAK;EACnC,QAAQ,gBAAgB,yBAAyB,OAAO,IAAI,eAAe;EAC3E,QAAQ,SAAS,aAAa;;EAmH9B;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA,SAAS,UAAU;;;;;;;;;EAanB,WAAW;;;;;;;UA8BH;;EA6CR;;;;;;;;;;;UA0BQ;UA4FA;;;;;;;;;;;UAwDA;UAuBA"}
|
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.3.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}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{i as getMetaRecord,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,r as getMetaMap,t as getClassMeta}from"./metadata-C2GK_17k.mjs";import"reflect-metadata";let impl=null;function _setAssetResolver(fn){impl=fn}function resolveAssetViaSlot(namespace,key){if(!impl)throw Error(`@Asset('${namespace}/${key}'): the asset manager is not loaded. Import it (any import from '@forinda/kickjs' loads it) — note @Asset reads from the filesystem and is not supported on edge runtimes.`);return impl(namespace,key)}var KickError=class extends Error{code;summary;cause;fix;docsUrl;context;constructor(init){super(formatKickError(init,{color:!1})),this.name=`KickError`,this.code=init.code,this.summary=init.summary,init.cause!==void 0&&(this.cause=init.cause),init.fix!==void 0&&(this.fix=init.fix),init.docsUrl!==void 0&&(this.docsUrl=init.docsUrl),init.context!==void 0&&(this.context=init.context)}};function ansiEnabled(){return process.env.NO_COLOR?!1:process.env.FORCE_COLOR?!0:process.stderr?.isTTY===!0}function paint(text,code,enabled){return enabled?`[${code}m${text}[0m`:text}const c={red:(s,enabled)=>paint(s,`31`,enabled),bold:(s,enabled)=>paint(s,`1`,enabled),dim:(s,enabled)=>paint(s,`2`,enabled),cyan:(s,enabled)=>paint(s,`36`,enabled),blue:(s,enabled)=>paint(s,`34`,enabled),underline:(s,enabled)=>paint(s,`4`,enabled)};function formatKickError(err,options={}){let color=options.color??ansiEnabled(),lines=[],code=c.bold(c.red(err.code,color),color);if(lines.push(`${code}: ${err.summary}`),err.cause){lines.push(``,` ${c.bold(c.dim(`Cause:`,color),color)}`);for(let line of err.cause.split(`
|
|
12
|
-
`))lines.push(` ${highlightInline(line,color)}`)}if(err.fix){lines.push(``,` ${c.bold(c.dim(`Fix:`,color),color)}`);for(let line of err.fix.split(`
|
|
13
|
-
`))lines.push(` ${highlightInline(line,color)}`)}return err.docsUrl&&(lines.push(``,` ${c.bold(c.dim(`Docs:`,color),color)}`),lines.push(` ${c.underline(c.blue(err.docsUrl,color),color)}`)),lines.join(`
|
|
14
|
-
`)}function highlightInline(line,color){return color?line.replace(/`([^`]+)`/g,(_,inner)=>`\`${c.cyan(inner,!0)}\``):line}const DOCS_BASE=`https://kickjs.app`;function noProviderError(tokenName){return new KickError({code:`KICK001`,summary:`No provider for ${tokenName}`,cause:`\`${tokenName}\` was requested from the DI container but no binding is registered.
|
|
15
|
-
This usually means one of:
|
|
16
|
-
• The class is decorated with @Service() / @Repository() / @Controller(),
|
|
17
|
-
but its enclosing module isn't passed to bootstrap({ modules: [...] }).
|
|
18
|
-
• The class isn't decorated at all (decorators register the binding).
|
|
19
|
-
• You're injecting a token (created with createToken()) that nothing
|
|
20
|
-
provides — add a Container.register(TOKEN, ...) call or a module that
|
|
21
|
-
binds it.`,fix:`If \`${tokenName}\` lives in a module, add the module to bootstrap:
|
|
22
|
-
|
|
23
|
-
bootstrap({
|
|
24
|
-
modules: [
|
|
25
|
-
UsersModule, // add this
|
|
26
|
-
OtherModule,
|
|
27
|
-
],
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
If it's a custom token, register it explicitly:
|
|
31
|
-
|
|
32
|
-
const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')
|
|
33
|
-
Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#registering-services`,context:{token:tokenName}})}function requestScopeMiddlewareMissingError(tokenName){return new KickError({code:`KICK002`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" — request scope middleware not mounted`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` but no AsyncLocalStorage frame is wired.
|
|
34
|
-
The framework's request-scope middleware sets up that frame; without it,
|
|
35
|
-
REQUEST-scoped resolutions have nowhere to cache the per-request instance.`,fix:`Add \`requestScopeMiddleware()\` to your global middleware pipeline,
|
|
36
|
-
or let the framework auto-mount it by using \`contextStore: 'auto'\`
|
|
37
|
-
(the default — only check this if you set it to 'manual' explicitly):
|
|
38
|
-
|
|
39
|
-
bootstrap({
|
|
40
|
-
modules,
|
|
41
|
-
// contextStore: 'auto', // default; no need to set
|
|
42
|
-
})
|
|
43
|
-
|
|
44
|
-
If you set \`contextStore: 'manual'\` deliberately (rare), you own the
|
|
45
|
-
ALS wrapping — call \`requestStore.run({...}, () => ...)\` around the
|
|
46
|
-
code that resolves the binding.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function requestScopeOutsideRequestError(tokenName){return new KickError({code:`KICK003`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" outside an HTTP request`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` and was resolved outside
|
|
47
|
-
any HTTP request context. The request-scope middleware is wired, but
|
|
48
|
-
the call happened before a request started (e.g. in a top-level
|
|
49
|
-
import, a constructor, a cron job, a test without setup).`,fix:`If the caller is request-scoped (controller, request-scoped service),
|
|
50
|
-
make sure the call happens inside the request lifecycle, not at module
|
|
51
|
-
load time.
|
|
52
|
-
|
|
53
|
-
In tests, wrap setup in an ALS frame manually:
|
|
54
|
-
|
|
55
|
-
import { requestStore } from '@forinda/kickjs'
|
|
56
|
-
|
|
57
|
-
requestStore.run(
|
|
58
|
-
{ requestId: 'test', instances: new Map(), values: new Map() },
|
|
59
|
-
() => {
|
|
60
|
-
const svc = container.resolve(MyRequestScopedService)
|
|
61
|
-
// ...
|
|
62
|
-
},
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
If the caller is a SINGLETON, change \`${tokenName}\` to TRANSIENT or
|
|
66
|
-
SINGLETON scope, or inject a factory instead of the instance directly.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function envValueMissingError(envKey){return new KickError({code:`KICK004`,summary:`@Value('${envKey}'): environment variable not set and no default provided`,cause:`\`@Value('${envKey}')\` resolved but the env var isn't present and the
|
|
67
|
-
decorator didn't declare a default. Possible reasons:
|
|
68
|
-
• The variable is genuinely missing from your environment / .env file.
|
|
69
|
-
• Your \`src/env.ts\` calls \`loadEnv(envSchema)\` but \`src/index.ts\`
|
|
70
|
-
doesn't import \`./env\` before \`bootstrap()\`. Without that import
|
|
71
|
-
the schema never runs and ConfigService stays empty — \`@Value\`
|
|
72
|
-
only finds the var via the \`process.env\` fallback.`,fix:`Either set the variable in your shell / .env file:
|
|
73
|
-
|
|
74
|
-
${envKey}=...
|
|
75
|
-
|
|
76
|
-
Or add a default at the decorator:
|
|
77
|
-
|
|
78
|
-
@Value('${envKey}', { default: 'fallback' })
|
|
79
|
-
private value!: string
|
|
80
|
-
|
|
81
|
-
If you're using a schema, make sure \`src/env.ts\` is imported from
|
|
82
|
-
\`src/index.ts\` BEFORE bootstrap runs:
|
|
83
|
-
|
|
84
|
-
// src/index.ts
|
|
85
|
-
import 'reflect-metadata'
|
|
86
|
-
import './env' // ← this line is required
|
|
87
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
88
|
-
// ...`,docsUrl:`${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,context:{envKey}})}function moduleRouteMissingControllerError(mountPath){return new KickError({code:`KICK005`,summary:`Module route at ${mountPath} requires either 'controller' or 'router'`,cause:`A module's \`routes()\` returned an entry for \`${mountPath}\` but didn't
|
|
89
|
-
specify how to build the router. The framework needs either a decorated
|
|
90
|
-
controller class (it calls \`buildRoutes()\` internally) or a hand-built
|
|
91
|
-
Express Router.`,fix:`Pass \`controller:\` for the common case:
|
|
92
|
-
|
|
93
|
-
routes() {
|
|
94
|
-
return {
|
|
95
|
-
path: '${mountPath}',
|
|
96
|
-
controller: UsersController,
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
Or pass \`router:\` for full control:
|
|
101
|
-
|
|
102
|
-
routes() {
|
|
103
|
-
return {
|
|
104
|
-
path: '${mountPath}',
|
|
105
|
-
router: myExpressRouter,
|
|
106
|
-
}
|
|
107
|
-
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{mountPath}})}function duplicateRouteError(method,path,owner,prior){return new KickError({code:`KICK006`,summary:`Duplicate route: ${method} ${path} is registered twice`,cause:`\`${owner}\` registers \`${method} ${path}\`, but that verb + path is
|
|
108
|
-
already claimed by \`${prior}\`. Only one handler can win at dispatch
|
|
109
|
-
time, and which one depends on the engine — while \`kick typegen\` and
|
|
110
|
-
the typed client may describe the other. Param names are ignored when
|
|
111
|
-
comparing (\`/:id\` and \`/:taskId\` are the same route).`,fix:`Change one of the two paths, remove the duplicate handler, or mount
|
|
112
|
-
the second controller under a different module path / version:
|
|
113
|
-
|
|
114
|
-
routes() {
|
|
115
|
-
return { path: '/tasks', controller: TasksController, version: 2 }
|
|
116
|
-
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{method,path,owner,prior}})}function http2UnsupportedRuntimeError(runtime){return new KickError({code:`KICK007`,summary:`The ${runtime} runtime cannot serve HTTP/2`,cause:`\`bootstrap({ server: { http2: true } })\` asks for an HTTP/2 server, but the
|
|
117
|
-
\`${runtime}\` runtime does not support Node's HTTP/2 compatibility layer —
|
|
118
|
-
requests would hang instead of being answered.`,fix:`Pick one:
|
|
119
|
-
• Switch to a runtime that serves HTTP/2:
|
|
120
|
-
bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })
|
|
121
|
-
(or h3Runtime()).
|
|
122
|
-
• Drop \`http2\` and keep HTTPS over HTTP/1.1: server: { tls }.
|
|
123
|
-
• Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{runtime}})}function http2RequiresTlsError(){return new KickError({code:`KICK008`,summary:`server.http2 requires server.tls`,cause:"`bootstrap({ server: { http2: true } })` was set without `tls`. Browsers only\nnegotiate HTTP/2 over TLS, and KickJS does not serve cleartext HTTP/2 (h2c).",fix:`Pass the certificate and key alongside http2:
|
|
124
|
-
|
|
125
|
-
server: {
|
|
126
|
-
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
|
127
|
-
http2: true,
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
Or remove \`http2\` if TLS is terminated in front of the app.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`})}function tlsCredentialsError(problem){return new KickError({code:`KICK009`,summary:`server.tls is not usable: ${problem}`,cause:`\`bootstrap({ server: { tls } })\` was given TLS options the server cannot use:
|
|
131
|
-
${problem}. Node would start anyway and fail every TLS handshake.`,fix:"Give the server an identity:\n • `key` and `cert` together (PEM, matching each other), or\n • `pfx` (with `passphrase` if it is encrypted), or\n • `SNICallback` / `pskCallback` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }",docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{problem}})}const INJECTION_TOKEN=Symbol.for(`@kickjs/InjectionToken`);function createToken(name){return Object.freeze({[INJECTION_TOKEN]:!0,name})}function isInjectionToken(value){return typeof value==`object`&&!!value&&value[INJECTION_TOKEN]===!0}const log=createLogger(`Container`);function createReg(fields){return{kind:`unknown`,resolveCount:0,postConstructStatus:`skipped`,dependencies:[],...fields}}function tokenName(token){return typeof token==`symbol`?token.toString():isInjectionToken(token)?token.name:token?.name||String(token)}function getPersistentStore(){return globalThis.__kickjs_persistent||(globalThis.__kickjs_persistent={factories:[],instances:[],resolvedInstances:/* @__PURE__ */ new Map}),globalThis.__kickjs_persistent}var Container=class Container{static instance;registrations=/* @__PURE__ */ new Map;resolving=/* @__PURE__ */ new Set;changeListeners=/* @__PURE__ */ new Set;pendingChanges=[];notifyTimer=null;static DEBOUNCE_MS=50;static _onReady=null;static _onReset=null;static _onCreate=null;static _envResolver=null;isGlobal=!1;static _requestStoreProvider=null;static getInstance(){return Container.instance||(Container.instance=new Container,Container.instance.isGlobal=!0),Container._onReady&&=(Container._onReady(Container.instance),null),Container.instance}static reset(){Container.instance=new Container,Container.instance.isGlobal=!0,Container._onReset?.(Container.instance);let store=getPersistentStore();for(let{token,factory,scope}of store.factories)if(!Container.instance.has(token)){let name=tokenName(token),existing=store.resolvedInstances.get(name);Container.instance.registrations.set(token,createReg({target:Object,scope,factory,kind:`factory`,instance:existing,resolveCount:+!!existing,postConstructStatus:existing?`completed`:`skipped`}))}for(let{token,instance}of store.instances)Container.instance.has(token)||Container.instance.registrations.set(token,createReg({target:instance.constructor,scope:`singleton`,instance,kind:`instance`,postConstructStatus:`completed`,resolveCount:1}))}static create(){let container=new Container;return Container._onCreate?.(container),container}register(token,target,scope=`singleton`){let kind=getClassMeta(METADATA.CLASS_KIND,target,`unknown`),reg=createReg({target,scope,kind,dependencies:this.extractDependencies(target)});this.registrations.set(token,reg),typeof token==`function`&&token.name&&this.registrations.set(`__hmr__${token.name}`,reg),this.emit(token,`registered`,kind)}registerFactory(token,factory,scope=`singleton`){let store=getPersistentStore(),name=tokenName(token),factoryUnchanged=(this.isGlobal?store.factories.find(r=>tokenName(r.token)===name):void 0)?.factory===factory,existingInstance=this.isGlobal&&factoryUnchanged?store.resolvedInstances.get(name):void 0;if(this.isGlobal&&!factoryUnchanged&&store.resolvedInstances.delete(name),this.registrations.set(token,createReg({target:Object,scope,factory,kind:`factory`,instance:existingInstance,resolveCount:+!!existingInstance,postConstructStatus:existingInstance?`completed`:`skipped`})),this.isGlobal){let idx=store.factories.findIndex(r=>tokenName(r.token)===name);idx>=0?store.factories[idx]={token,factory,scope}:store.factories.push({token,factory,scope})}this.emit(name,`registered`,`factory`)}registerInstance(token,instance){let store=getPersistentStore(),name=tokenName(token);if(this.registrations.set(token,createReg({target:instance.constructor,scope:`singleton`,instance,kind:`instance`,postConstructStatus:`completed`,resolveCount:1,firstResolvedAt:Date.now(),lastResolvedAt:Date.now()})),this.isGlobal){store.resolvedInstances.set(name,instance);let idx=store.instances.findIndex(r=>tokenName(r.token)===name);idx>=0?store.instances[idx]={token,instance}:store.instances.push({token,instance})}this.emit(name,`registered`,`instance`)}has(token){return this.registrations.has(token)}getRegistrations(){let entries=[];for(let[token,reg]of this.registrations)entries.push({token:tokenName(token),scope:reg.scope,kind:reg.kind,instantiated:reg.scope===`singleton`?reg.instance!==void 0:reg.resolveCount>0,resolveCount:reg.resolveCount,lastResolvedAt:reg.lastResolvedAt,firstResolvedAt:reg.firstResolvedAt,resolveDurationMs:reg.resolveDurationMs,postConstructStatus:reg.postConstructStatus,dependencies:reg.dependencies});return entries}resolve(token){let reg=this.registrations.get(token);if(!reg&&typeof token==`function`&&token.name&&(reg=this.registrations.get(`__hmr__${token.name}`)),!reg)throw noProviderError(tokenName(token));if(reg.scope===`singleton`&®.instance!==void 0)return reg.resolveCount++,reg.lastResolvedAt=Date.now(),this.emit(token,`resolved`,reg.kind),reg.instance;if(reg.scope===`request`){if(!Container._requestStoreProvider)throw requestScopeMiddlewareMissingError(tokenName(token));let store=Container._requestStoreProvider();if(!store)throw requestScopeOutsideRequestError(tokenName(token));if(store.values.has(token))return reg.resolveCount++,reg.lastResolvedAt=Date.now(),this.emit(token,`resolved`,reg.kind),store.values.get(token);if(store.instances.has(token))return reg.resolveCount++,reg.lastResolvedAt=Date.now(),this.emit(token,`resolved`,reg.kind),store.instances.get(token);if(reg.factory){let start=performance.now(),instance=reg.factory();return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),store.instances.set(token,instance),this.emit(token,`resolved`,reg.kind),instance}let start=performance.now(),instance=this.createInstance(reg);return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),store.instances.set(token,instance),this.emit(token,`resolved`,reg.kind),instance}if(reg.factory){let start=performance.now(),instance=reg.factory();return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),reg.scope===`singleton`&&(reg.instance=instance,this.isGlobal&&getPersistentStore().resolvedInstances.set(tokenName(token),instance)),this.emit(token,`resolved`,reg.kind),instance}if(this.resolving.has(token)){let chain=[...this.resolving].map(tokenName);throw chain.push(tokenName(token)),Error(`Circular dependency detected: ${chain.join(` -> `)}`)}this.resolving.add(token);try{let start=performance.now(),instance=this.createInstance(reg);return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),reg.scope===`singleton`&&(reg.instance=instance),this.emit(token,`resolved`,reg.kind),instance}finally{this.resolving.delete(token)}}bootstrap(){}onChange(callback){return this.changeListeners.add(callback),()=>this.changeListeners.delete(callback)}invalidate(token){let name=tokenName(token),reg=this.registrations.get(token)??this.registrations.get(`__hmr__${name}`);if(reg&&!getPersistentStore().resolvedInstances.has(name)){reg.instance=void 0,reg.resolveCount=0,reg.postConstructStatus=`skipped`,this.emit(name,`invalidated`,reg.kind);for(let[depToken,depReg]of this.registrations)depReg.dependencies.includes(name)&&this.invalidate(depToken)}}emit(rawToken,event,kind){if(this.changeListeners.size===0)return;let token=tokenName(rawToken),existing=this.pendingChanges.find(p=>p.token===token&&p.event===event);existing?existing.timestamp=Date.now():this.pendingChanges.push({token,event,kind,timestamp:Date.now()}),this.notifyTimer&&clearTimeout(this.notifyTimer),this.notifyTimer=setTimeout(()=>{let batch=this.pendingChanges.splice(0);if(batch.length!==0)for(let listener of this.changeListeners)try{listener(batch)}catch{}},Container.DEBOUNCE_MS),this.notifyTimer.unref?.()}flushChanges(){this.notifyTimer&&=(clearTimeout(this.notifyTimer),null);let batch=this.pendingChanges.splice(0);if(batch.length!==0)for(let listener of this.changeListeners)try{listener(batch)}catch{}}buildPlan(reg){let paramTypes=getClassMeta(METADATA.PARAM_TYPES,reg.target,[]),injectTokens=getMetaRecord(METADATA.INJECT,reg.target),maxInjectIndex=Object.keys(injectTokens).length>0?Math.max(...Object.keys(injectTokens).map(Number))+1:0,paramCount=Math.max(paramTypes.length,maxInjectIndex),ctorTokens=[];for(let index=0;index<paramCount;index++){let token=injectTokens[index]||paramTypes[index];if(!token)throw Error(`Cannot resolve constructor parameter at index ${index} of ${tokenName(reg.target)}. No @Inject token and no design:paramtypes metadata (tsx/ts-node don't emit it). Add @Inject(Token) to every constructor parameter.`);if(reg.scope===`singleton`){let depReg=this.registrations.get(token);if(depReg&&depReg.scope===`request`){let parent=tokenName(reg.target),dep=tokenName(token),fix=getClassMetaOrUndefined(METADATA.CLASS_KIND,reg.target)===`controller`?`@Controller() is always SINGLETON, so inject "${dep}" with @Autowired() instead of the constructor.`:`Give "${parent}" TRANSIENT or REQUEST scope (e.g. @Service({ scope: Scope.REQUEST })), or inject "${dep}" with @Autowired() instead of the constructor.`;throw Error(`Cannot inject REQUEST-scoped "${dep}" into SINGLETON "${parent}". Singletons outlive requests. ${fix}`)}}ctorTokens.push(token)}let autowiredProps=getMetaMap(METADATA.AUTOWIRED,reg.target.prototype),autowired=[];for(let[prop,token]of autowiredProps){let resolvedToken=token||getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE,reg.target.prototype,prop);resolvedToken&&autowired.push([prop,resolvedToken])}let values=[...getMetaMap(METADATA.VALUE,reg.target.prototype).entries()],assetProps=getMetaMap(METADATA.ASSET,reg.target.prototype),assets=[];for(let[prop,config]of assetProps){let slashIdx=config.assetKey.indexOf(`/`);if(slashIdx===-1)throw Error(`@Asset('${config.assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);assets.push([prop,{namespace:config.assetKey.slice(0,slashIdx),key:config.assetKey.slice(slashIdx+1)}])}return{ctorTokens,autowired,values,assets,postConstruct:getClassMetaOrUndefined(METADATA.POST_CONSTRUCT,reg.target.prototype)}}createInstance(reg){let plan=reg.plan??=this.buildPlan(reg),args=[];for(let token of plan.ctorTokens)args.push(this.resolve(token));let instance=new reg.target(...args);this.injectProperties(instance,plan);let postConstruct=plan.postConstruct;if(postConstruct&&typeof instance[postConstruct]==`function`)try{let result=instance[postConstruct]();result&&typeof result.then==`function`?(reg.postConstructStatus=`pending`,result.then(()=>{reg.postConstructStatus=`completed`}).catch(()=>{reg.postConstructStatus=`failed`}),log.warn(`@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise but the container is synchronous. The async operation will not be awaited.`)):reg.postConstructStatus=`completed`}catch(err){reg.postConstructStatus=`failed`,log.error(err,`@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`)}return instance}extractDependencies(target){let paramTypes=getClassMeta(METADATA.PARAM_TYPES,target,[]),injectTokens=getMetaRecord(METADATA.INJECT,target),ctorDeps=paramTypes.map((type,index)=>tokenName(injectTokens[index]||type)),autowiredProps=getMetaMap(METADATA.AUTOWIRED,target.prototype),propDeps=[];for(let[prop,token]of autowiredProps){let resolvedToken=token||getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE,target.prototype,prop);resolvedToken&&propDeps.push(tokenName(resolvedToken))}return[.../* @__PURE__ */ new Set([...ctorDeps,...propDeps])]}injectProperties(instance,plan){for(let[prop,resolvedToken]of plan.autowired)Object.defineProperty(instance,prop,{get:()=>{let value=this.resolve(resolvedToken);return this.registrations.get(resolvedToken)?.scope===`singleton`&&Object.defineProperty(instance,prop,{value,enumerable:!0,configurable:!0,writable:!1}),value},enumerable:!0,configurable:!0});for(let[prop,config]of plan.values)Object.defineProperty(instance,prop,{get(){if(Container._envResolver){let val=Container._envResolver(config.envKey);if(val!==void 0)return val}let val=process.env[config.envKey];if(val!==void 0)return val;if(config.defaultValue!==void 0)return config.defaultValue;throw envValueMissingError(config.envKey)},enumerable:!0,configurable:!0});for(let[prop,{namespace,key}]of plan.assets)Object.defineProperty(instance,prop,{get(){return resolveAssetViaSlot(namespace,key)},enumerable:!0,configurable:!0})}};export{isInjectionToken as a,http2UnsupportedRuntimeError as c,KickError as d,formatKickError as f,createToken as i,moduleRouteMissingControllerError as l,tokenName as n,duplicateRouteError as o,_setAssetResolver as p,INJECTION_TOKEN as r,http2RequiresTlsError as s,Container as t,tlsCredentialsError as u};
|
|
132
|
-
//# sourceMappingURL=container-mvaAYThX.mjs.map
|