@navios/di 0.8.0 → 0.9.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.
Files changed (264) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +117 -17
  3. package/lib/browser/container/abstract-container.d.mts +112 -0
  4. package/lib/browser/container/abstract-container.d.mts.map +1 -0
  5. package/lib/browser/container/abstract-container.mjs +100 -0
  6. package/lib/browser/container/abstract-container.mjs.map +1 -0
  7. package/lib/browser/container/container.d.mts +100 -0
  8. package/lib/browser/container/container.d.mts.map +1 -0
  9. package/lib/browser/container/container.mjs +424 -0
  10. package/lib/browser/container/container.mjs.map +1 -0
  11. package/lib/browser/container/scoped-container.d.mts +93 -0
  12. package/lib/browser/container/scoped-container.d.mts.map +1 -0
  13. package/lib/browser/container/scoped-container.mjs +119 -0
  14. package/lib/browser/container/scoped-container.mjs.map +1 -0
  15. package/lib/browser/decorators/factory.decorator.d.mts +26 -0
  16. package/lib/browser/decorators/factory.decorator.d.mts.map +1 -0
  17. package/lib/browser/decorators/factory.decorator.mjs +20 -0
  18. package/lib/browser/decorators/factory.decorator.mjs.map +1 -0
  19. package/lib/browser/decorators/injectable.decorator.d.mts +38 -0
  20. package/lib/browser/decorators/injectable.decorator.d.mts.map +1 -0
  21. package/lib/browser/decorators/injectable.decorator.mjs +21 -0
  22. package/lib/browser/decorators/injectable.decorator.mjs.map +1 -0
  23. package/lib/browser/enums/injectable-scope.enum.d.mts +18 -0
  24. package/lib/browser/enums/injectable-scope.enum.d.mts.map +1 -0
  25. package/lib/browser/enums/injectable-scope.enum.mjs +20 -0
  26. package/lib/browser/enums/injectable-scope.enum.mjs.map +1 -0
  27. package/lib/browser/enums/injectable-type.enum.d.mts +8 -0
  28. package/lib/browser/enums/injectable-type.enum.d.mts.map +1 -0
  29. package/lib/browser/enums/injectable-type.enum.mjs +10 -0
  30. package/lib/browser/enums/injectable-type.enum.mjs.map +1 -0
  31. package/lib/browser/errors/di-error.d.mts +43 -0
  32. package/lib/browser/errors/di-error.d.mts.map +1 -0
  33. package/lib/browser/errors/di-error.mjs +98 -0
  34. package/lib/browser/errors/di-error.mjs.map +1 -0
  35. package/lib/browser/event-emitter.d.mts +16 -0
  36. package/lib/browser/event-emitter.d.mts.map +1 -0
  37. package/lib/browser/event-emitter.mjs +320 -0
  38. package/lib/browser/event-emitter.mjs.map +1 -0
  39. package/lib/browser/index.d.mts +37 -1558
  40. package/lib/browser/index.mjs +29 -2749
  41. package/lib/browser/interfaces/container.interface.d.mts +59 -0
  42. package/lib/browser/interfaces/container.interface.d.mts.map +1 -0
  43. package/lib/browser/interfaces/factory.interface.d.mts +14 -0
  44. package/lib/browser/interfaces/factory.interface.d.mts.map +1 -0
  45. package/lib/browser/interfaces/on-service-destroy.interface.d.mts +7 -0
  46. package/lib/browser/interfaces/on-service-destroy.interface.d.mts.map +1 -0
  47. package/lib/browser/interfaces/on-service-init.interface.d.mts +7 -0
  48. package/lib/browser/interfaces/on-service-init.interface.d.mts.map +1 -0
  49. package/lib/browser/internal/context/async-local-storage.browser.mjs +20 -0
  50. package/lib/browser/internal/context/async-local-storage.browser.mjs.map +1 -0
  51. package/lib/browser/internal/context/async-local-storage.d.mts +9 -0
  52. package/lib/browser/internal/context/async-local-storage.d.mts.map +1 -0
  53. package/lib/browser/internal/context/async-local-storage.types.d.mts +11 -0
  54. package/lib/browser/internal/context/async-local-storage.types.d.mts.map +1 -0
  55. package/lib/browser/internal/context/factory-context.d.mts +23 -0
  56. package/lib/browser/internal/context/factory-context.d.mts.map +1 -0
  57. package/lib/browser/internal/context/resolution-context.d.mts +43 -0
  58. package/lib/browser/internal/context/resolution-context.d.mts.map +1 -0
  59. package/lib/browser/internal/context/resolution-context.mjs +56 -0
  60. package/lib/browser/internal/context/resolution-context.mjs.map +1 -0
  61. package/lib/browser/internal/context/service-initialization-context.d.mts +48 -0
  62. package/lib/browser/internal/context/service-initialization-context.d.mts.map +1 -0
  63. package/lib/browser/internal/context/sync-local-storage.mjs +53 -0
  64. package/lib/browser/internal/context/sync-local-storage.mjs.map +1 -0
  65. package/lib/browser/internal/core/instance-resolver.d.mts +119 -0
  66. package/lib/browser/internal/core/instance-resolver.d.mts.map +1 -0
  67. package/lib/browser/internal/core/instance-resolver.mjs +306 -0
  68. package/lib/browser/internal/core/instance-resolver.mjs.map +1 -0
  69. package/lib/browser/internal/core/name-resolver.d.mts +52 -0
  70. package/lib/browser/internal/core/name-resolver.d.mts.map +1 -0
  71. package/lib/browser/internal/core/name-resolver.mjs +118 -0
  72. package/lib/browser/internal/core/name-resolver.mjs.map +1 -0
  73. package/lib/browser/internal/core/scope-tracker.d.mts +65 -0
  74. package/lib/browser/internal/core/scope-tracker.d.mts.map +1 -0
  75. package/lib/browser/internal/core/scope-tracker.mjs +120 -0
  76. package/lib/browser/internal/core/scope-tracker.mjs.map +1 -0
  77. package/lib/browser/internal/core/service-initializer.d.mts +44 -0
  78. package/lib/browser/internal/core/service-initializer.d.mts.map +1 -0
  79. package/lib/browser/internal/core/service-initializer.mjs +109 -0
  80. package/lib/browser/internal/core/service-initializer.mjs.map +1 -0
  81. package/lib/browser/internal/core/service-invalidator.d.mts +81 -0
  82. package/lib/browser/internal/core/service-invalidator.d.mts.map +1 -0
  83. package/lib/browser/internal/core/service-invalidator.mjs +142 -0
  84. package/lib/browser/internal/core/service-invalidator.mjs.map +1 -0
  85. package/lib/browser/internal/core/token-resolver.d.mts +54 -0
  86. package/lib/browser/internal/core/token-resolver.d.mts.map +1 -0
  87. package/lib/browser/internal/core/token-resolver.mjs +77 -0
  88. package/lib/browser/internal/core/token-resolver.mjs.map +1 -0
  89. package/lib/browser/internal/holder/holder-storage.interface.d.mts +99 -0
  90. package/lib/browser/internal/holder/holder-storage.interface.d.mts.map +1 -0
  91. package/lib/browser/internal/holder/instance-holder.d.mts +101 -0
  92. package/lib/browser/internal/holder/instance-holder.d.mts.map +1 -0
  93. package/lib/browser/internal/holder/instance-holder.mjs +19 -0
  94. package/lib/browser/internal/holder/instance-holder.mjs.map +1 -0
  95. package/lib/browser/internal/holder/unified-storage.d.mts +53 -0
  96. package/lib/browser/internal/holder/unified-storage.d.mts.map +1 -0
  97. package/lib/browser/internal/holder/unified-storage.mjs +144 -0
  98. package/lib/browser/internal/holder/unified-storage.mjs.map +1 -0
  99. package/lib/browser/internal/lifecycle/circular-detector.d.mts +39 -0
  100. package/lib/browser/internal/lifecycle/circular-detector.d.mts.map +1 -0
  101. package/lib/browser/internal/lifecycle/circular-detector.mjs +55 -0
  102. package/lib/browser/internal/lifecycle/circular-detector.mjs.map +1 -0
  103. package/lib/browser/internal/lifecycle/lifecycle-event-bus.d.mts +18 -0
  104. package/lib/browser/internal/lifecycle/lifecycle-event-bus.d.mts.map +1 -0
  105. package/lib/browser/internal/lifecycle/lifecycle-event-bus.mjs +43 -0
  106. package/lib/browser/internal/lifecycle/lifecycle-event-bus.mjs.map +1 -0
  107. package/lib/browser/internal/stub-factory-class.d.mts +14 -0
  108. package/lib/browser/internal/stub-factory-class.d.mts.map +1 -0
  109. package/lib/browser/internal/stub-factory-class.mjs +18 -0
  110. package/lib/browser/internal/stub-factory-class.mjs.map +1 -0
  111. package/lib/browser/symbols/injectable-token.d.mts +5 -0
  112. package/lib/browser/symbols/injectable-token.d.mts.map +1 -0
  113. package/lib/browser/symbols/injectable-token.mjs +6 -0
  114. package/lib/browser/symbols/injectable-token.mjs.map +1 -0
  115. package/lib/browser/token/injection-token.d.mts +55 -0
  116. package/lib/browser/token/injection-token.d.mts.map +1 -0
  117. package/lib/browser/token/injection-token.mjs +100 -0
  118. package/lib/browser/token/injection-token.mjs.map +1 -0
  119. package/lib/browser/token/registry.d.mts +37 -0
  120. package/lib/browser/token/registry.d.mts.map +1 -0
  121. package/lib/browser/token/registry.mjs +86 -0
  122. package/lib/browser/token/registry.mjs.map +1 -0
  123. package/lib/browser/utils/default-injectors.d.mts +12 -0
  124. package/lib/browser/utils/default-injectors.d.mts.map +1 -0
  125. package/lib/browser/utils/default-injectors.mjs +13 -0
  126. package/lib/browser/utils/default-injectors.mjs.map +1 -0
  127. package/lib/browser/utils/get-injectable-token.d.mts +9 -0
  128. package/lib/browser/utils/get-injectable-token.d.mts.map +1 -0
  129. package/lib/browser/utils/get-injectable-token.mjs +13 -0
  130. package/lib/browser/utils/get-injectable-token.mjs.map +1 -0
  131. package/lib/browser/utils/get-injectors.d.mts +55 -0
  132. package/lib/browser/utils/get-injectors.d.mts.map +1 -0
  133. package/lib/browser/utils/get-injectors.mjs +121 -0
  134. package/lib/browser/utils/get-injectors.mjs.map +1 -0
  135. package/lib/browser/utils/types.d.mts +23 -0
  136. package/lib/browser/utils/types.d.mts.map +1 -0
  137. package/lib/{container-DAKOvAgr.mjs → container-8-z89TyQ.mjs} +1325 -1462
  138. package/lib/container-8-z89TyQ.mjs.map +1 -0
  139. package/lib/{container-Bp1W-pWJ.d.mts → container-CNiqesCL.d.mts} +598 -617
  140. package/lib/container-CNiqesCL.d.mts.map +1 -0
  141. package/lib/{container-DENMeJ87.cjs → container-CaY2fDuk.cjs} +1369 -1512
  142. package/lib/container-CaY2fDuk.cjs.map +1 -0
  143. package/lib/{container-YPwvmlK2.d.cts → container-D-0Ho3qL.d.cts} +598 -612
  144. package/lib/container-D-0Ho3qL.d.cts.map +1 -0
  145. package/lib/index.cjs +13 -15
  146. package/lib/index.cjs.map +1 -1
  147. package/lib/index.d.cts +58 -223
  148. package/lib/index.d.cts.map +1 -1
  149. package/lib/index.d.mts +62 -222
  150. package/lib/index.d.mts.map +1 -1
  151. package/lib/index.mjs +5 -6
  152. package/lib/index.mjs.map +1 -1
  153. package/lib/testing/index.cjs +569 -311
  154. package/lib/testing/index.cjs.map +1 -1
  155. package/lib/testing/index.d.cts +370 -41
  156. package/lib/testing/index.d.cts.map +1 -1
  157. package/lib/testing/index.d.mts +370 -41
  158. package/lib/testing/index.d.mts.map +1 -1
  159. package/lib/testing/index.mjs +568 -305
  160. package/lib/testing/index.mjs.map +1 -1
  161. package/package.json +2 -1
  162. package/src/__tests__/circular-detector.spec.mts +193 -0
  163. package/src/__tests__/concurrent.spec.mts +368 -0
  164. package/src/__tests__/container.spec.mts +32 -30
  165. package/src/__tests__/di-error.spec.mts +351 -0
  166. package/src/__tests__/e2e.browser.spec.mts +0 -4
  167. package/src/__tests__/e2e.spec.mts +10 -19
  168. package/src/__tests__/event-emitter.spec.mts +232 -109
  169. package/src/__tests__/get-injectors.spec.mts +250 -39
  170. package/src/__tests__/injection-token.spec.mts +293 -349
  171. package/src/__tests__/library-findings.spec.mts +8 -8
  172. package/src/__tests__/registry.spec.mts +358 -210
  173. package/src/__tests__/resolution-context.spec.mts +255 -0
  174. package/src/__tests__/scope-tracker.spec.mts +598 -0
  175. package/src/__tests__/scope-upgrade.spec.mts +808 -0
  176. package/src/__tests__/scoped-container.spec.mts +595 -0
  177. package/src/__tests__/test-container.spec.mts +293 -0
  178. package/src/__tests__/token-resolver.spec.mts +207 -0
  179. package/src/__tests__/unified-storage.spec.mts +535 -0
  180. package/src/__tests__/unit-test-container.spec.mts +405 -0
  181. package/src/__type-tests__/container.spec-d.mts +180 -0
  182. package/src/__type-tests__/factory.spec-d.mts +15 -3
  183. package/src/__type-tests__/inject.spec-d.mts +115 -20
  184. package/src/__type-tests__/injectable.spec-d.mts +69 -52
  185. package/src/__type-tests__/injection-token.spec-d.mts +176 -0
  186. package/src/__type-tests__/scoped-container.spec-d.mts +212 -0
  187. package/src/container/abstract-container.mts +327 -0
  188. package/src/container/container.mts +142 -170
  189. package/src/container/scoped-container.mts +126 -208
  190. package/src/decorators/factory.decorator.mts +16 -11
  191. package/src/decorators/injectable.decorator.mts +20 -16
  192. package/src/enums/index.mts +2 -2
  193. package/src/enums/injectable-scope.enum.mts +1 -0
  194. package/src/enums/injectable-type.enum.mts +1 -0
  195. package/src/errors/di-error.mts +96 -0
  196. package/src/event-emitter.mts +3 -27
  197. package/src/index.mts +6 -153
  198. package/src/interfaces/container.interface.mts +13 -0
  199. package/src/interfaces/factory.interface.mts +1 -1
  200. package/src/interfaces/index.mts +1 -1
  201. package/src/internal/context/async-local-storage.mts +3 -2
  202. package/src/internal/context/async-local-storage.types.mts +1 -0
  203. package/src/internal/context/factory-context.mts +1 -0
  204. package/src/internal/context/index.mts +3 -1
  205. package/src/internal/context/resolution-context.mts +1 -0
  206. package/src/internal/context/service-initialization-context.mts +43 -0
  207. package/src/internal/core/index.mts +5 -4
  208. package/src/internal/core/instance-resolver.mts +460 -302
  209. package/src/internal/core/name-resolver.mts +196 -0
  210. package/src/internal/core/scope-tracker.mts +242 -0
  211. package/src/internal/core/{instantiator.mts → service-initializer.mts} +51 -29
  212. package/src/internal/core/service-invalidator.mts +290 -0
  213. package/src/internal/core/token-resolver.mts +122 -0
  214. package/src/internal/holder/holder-storage.interface.mts +11 -5
  215. package/src/internal/holder/index.mts +2 -5
  216. package/src/internal/holder/instance-holder.mts +1 -3
  217. package/src/internal/holder/unified-storage.mts +245 -0
  218. package/src/internal/index.mts +2 -1
  219. package/src/internal/lifecycle/circular-detector.mts +1 -0
  220. package/src/internal/lifecycle/index.mts +1 -1
  221. package/src/internal/lifecycle/lifecycle-event-bus.mts +1 -0
  222. package/src/internal/stub-factory-class.mts +16 -0
  223. package/src/symbols/injectable-token.mts +3 -1
  224. package/src/testing/index.mts +2 -0
  225. package/src/testing/test-container.mts +546 -85
  226. package/src/testing/types.mts +117 -0
  227. package/src/testing/unit-test-container.mts +509 -0
  228. package/src/token/injection-token.mts +41 -4
  229. package/src/token/registry.mts +75 -9
  230. package/src/utils/default-injectors.mts +16 -0
  231. package/src/utils/get-injectable-token.mts +2 -3
  232. package/src/utils/get-injectors.mts +26 -15
  233. package/src/utils/index.mts +3 -1
  234. package/src/utils/types.mts +1 -0
  235. package/tsdown.config.mts +11 -1
  236. package/lib/browser/index.d.mts.map +0 -1
  237. package/lib/browser/index.mjs.map +0 -1
  238. package/lib/container-Bp1W-pWJ.d.mts.map +0 -1
  239. package/lib/container-DAKOvAgr.mjs.map +0 -1
  240. package/lib/container-DENMeJ87.cjs.map +0 -1
  241. package/lib/container-YPwvmlK2.d.cts.map +0 -1
  242. package/src/__tests__/async-local-storage.browser.spec.mts +0 -166
  243. package/src/__tests__/async-local-storage.spec.mts +0 -333
  244. package/src/__tests__/errors.spec.mts +0 -87
  245. package/src/__tests__/factory.spec.mts +0 -137
  246. package/src/__tests__/injectable.spec.mts +0 -246
  247. package/src/__tests__/request-scope.spec.mts +0 -416
  248. package/src/__tests__/service-instantiator.spec.mts +0 -410
  249. package/src/__tests__/service-locator-event-bus.spec.mts +0 -242
  250. package/src/__tests__/service-locator-manager.spec.mts +0 -300
  251. package/src/__tests__/service-locator.spec.mts +0 -966
  252. package/src/__tests__/unified-api.spec.mts +0 -130
  253. package/src/browser.mts +0 -11
  254. package/src/injectors.mts +0 -18
  255. package/src/internal/context/request-context.mts +0 -225
  256. package/src/internal/core/invalidator.mts +0 -437
  257. package/src/internal/core/service-locator.mts +0 -202
  258. package/src/internal/core/token-processor.mts +0 -252
  259. package/src/internal/holder/base-holder-manager.mts +0 -334
  260. package/src/internal/holder/holder-manager.mts +0 -85
  261. package/src/internal/holder/request-storage.mts +0 -127
  262. package/src/internal/holder/singleton-storage.mts +0 -92
  263. package/src/testing/README.md +0 -80
  264. package/src/testing/__tests__/test-container.spec.mts +0 -173
@@ -1,5 +1,55 @@
1
1
  import { ZodObject, ZodOptional, ZodRecord, ZodType, z } from "zod/v4";
2
2
 
3
+ //#region src/token/injection-token.d.mts
4
+ type ClassType = new (...args: any[]) => any;
5
+ type ClassTypeWithoutArguments = new () => any;
6
+ type ClassTypeWithArgument<Arg> = new (arg: Arg) => any;
7
+ type ClassTypeWithOptionalArgument<Arg> = new (arg?: Arg) => any;
8
+ type ClassTypeWithInstance<T> = new (...args: any[]) => T;
9
+ type ClassTypeWithInstanceAndArgument<T, Arg> = new (arg: Arg) => T;
10
+ type ClassTypeWithInstanceAndOptionalArgument<T, Arg> = new (arg?: Arg) => T;
11
+ type BaseInjectionTokenSchemaType = ZodObject | ZodRecord;
12
+ type OptionalInjectionTokenSchemaType = ZodOptional<ZodObject> | ZodOptional<ZodRecord>;
13
+ type InjectionTokenSchemaType = BaseInjectionTokenSchemaType | OptionalInjectionTokenSchemaType;
14
+ declare class InjectionToken<T, S extends InjectionTokenSchemaType | unknown = unknown, Required extends boolean = (S extends ZodOptional<ZodObject> ? false : S extends ZodOptional<ZodRecord> ? false : S extends ZodObject ? true : S extends ZodRecord ? true : false)> {
15
+ readonly name: string | symbol | ClassType;
16
+ readonly schema: ZodObject | undefined;
17
+ readonly id: string;
18
+ private formattedName;
19
+ constructor(name: string | symbol | ClassType, schema: ZodObject | undefined, customId?: string);
20
+ static create<T extends ClassType>(name: T): InjectionToken<InstanceType<T>, undefined>;
21
+ static create<T extends ClassType, Schema extends InjectionTokenSchemaType>(name: T, schema: Schema): Schema['_def']['type'] extends 'ZodOptional' ? InjectionToken<InstanceType<T>, Schema, false> : InjectionToken<InstanceType<T>, Schema, true>;
22
+ static create<T>(name: string | symbol): InjectionToken<T, undefined>;
23
+ static create<T, Schema extends InjectionTokenSchemaType>(name: string | any, schema: Schema): InjectionToken<T, Schema>;
24
+ static bound<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, value: z.input<S>): BoundInjectionToken<T, S>;
25
+ static factory<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>): FactoryInjectionToken<T, S>;
26
+ static refineType<T>(token: BoundInjectionToken<any, any>): BoundInjectionToken<T, any>;
27
+ toString(): string;
28
+ }
29
+ declare class BoundInjectionToken<T, S extends InjectionTokenSchemaType> {
30
+ readonly token: InjectionToken<T, S>;
31
+ readonly value: z.input<S>;
32
+ id: string;
33
+ name: string | symbol | ClassType;
34
+ schema: InjectionTokenSchemaType;
35
+ constructor(token: InjectionToken<T, S>, value: z.input<S>);
36
+ toString(): string;
37
+ }
38
+ declare class FactoryInjectionToken<T, S extends InjectionTokenSchemaType> {
39
+ readonly token: InjectionToken<T, S>;
40
+ readonly factory: (ctx: FactoryContext) => Promise<z.input<S>>;
41
+ value?: z.input<S>;
42
+ resolved: boolean;
43
+ id: string;
44
+ name: string | symbol | ClassType;
45
+ schema: InjectionTokenSchemaType;
46
+ constructor(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>);
47
+ resolve(ctx: FactoryContext): Promise<z.input<S>>;
48
+ toString(): string;
49
+ }
50
+ type AnyInjectableType = ClassType | InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
51
+ type InjectionTokenType = InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
52
+ //#endregion
3
53
  //#region src/utils/types.d.mts
4
54
  type Join<TElements, TSeparator extends string> = TElements extends Readonly<[infer First, ...infer Rest]> ? Rest extends ReadonlyArray<string> ? First extends string ? `${First}${Rest extends [] ? '' : TSeparator}${Join<Rest, TSeparator>}` : never : never : '';
5
55
  type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
@@ -19,14 +69,6 @@ interface InjectState {
19
69
  requests: InjectRequest[];
20
70
  }
21
71
  //#endregion
22
- //#region src/interfaces/factory.interface.d.mts
23
- interface Factorable<T> {
24
- create(ctx?: FactoryContext): Promise<T> | T;
25
- }
26
- interface FactorableWithArgs<T, A extends InjectionTokenSchemaType> {
27
- create(ctx?: FactoryContext, ...args: [z.output<A>]): Promise<T> | T;
28
- }
29
- //#endregion
30
72
  //#region src/interfaces/container.interface.d.mts
31
73
  /**
32
74
  * Interface for dependency injection containers.
@@ -52,6 +94,15 @@ interface IContainer {
52
94
  * Checks if a service is registered in the container.
53
95
  */
54
96
  isRegistered(token: any): boolean;
97
+ /**
98
+ * Adds an instance to the container.
99
+ * Accepts class types, InjectionTokens, and BoundInjectionTokens.
100
+ * Rejects InjectionTokens with required schemas (use BoundInjectionToken instead).
101
+ *
102
+ * @param token The class type, InjectionToken, or BoundInjectionToken to register the instance for
103
+ * @param instance The instance to store
104
+ */
105
+ addInstance<T>(token: ClassType | InjectionToken<T, any> | BoundInjectionToken<T, any>, instance: T): void;
55
106
  /**
56
107
  * Disposes the container and cleans up all resources.
57
108
  */
@@ -69,6 +120,69 @@ interface IContainer {
69
120
  tryGetSync<T>(token: any, args?: any): T | null;
70
121
  }
71
122
  //#endregion
123
+ //#region src/enums/injectable-scope.enum.d.mts
124
+ declare enum InjectableScope {
125
+ /**
126
+ * Singleton scope: The instance is created once and shared across the application.
127
+ */
128
+ Singleton = "Singleton",
129
+ /**
130
+ * Instance scope: A new instance is created for each injection.
131
+ */
132
+ Transient = "Transient",
133
+ /**
134
+ * Request scope: The instance is created once per request and shared within that request context.
135
+ */
136
+ Request = "Request",
137
+ }
138
+ //#endregion
139
+ //#region src/enums/injectable-type.enum.d.mts
140
+ declare enum InjectableType {
141
+ Class = "Class",
142
+ Factory = "Factory",
143
+ }
144
+ //#endregion
145
+ //#region src/internal/context/service-initialization-context.d.mts
146
+ /**
147
+ * Context provided to injectors during service initialization.
148
+ *
149
+ * Extends FactoryContext with additional tracking information about
150
+ * the service being initialized, its dependencies, and scope.
151
+ * Used for scope upgrade tracking and dependency management.
152
+ */
153
+ interface ServiceInitializationContext {
154
+ inject: Injectors['asyncInject'];
155
+ /**
156
+ * The container instance for dependency resolution.
157
+ * This may be either a Container or ScopedContainer.
158
+ */
159
+ container: IContainer;
160
+ addDestroyListener: (listener: () => void) => void;
161
+ getDestroyListeners: () => (() => void)[];
162
+ /**
163
+ * The name of the service being initialized.
164
+ */
165
+ serviceName: string;
166
+ /**
167
+ * Set of dependency names that this service depends on.
168
+ * Automatically populated as dependencies are resolved.
169
+ */
170
+ dependencies: Set<string>;
171
+ /**
172
+ * The scope of the service being initialized.
173
+ */
174
+ scope: InjectableScope;
175
+ /**
176
+ * Track a dependency that was resolved.
177
+ * Used for scope upgrade tracking - if a Singleton service
178
+ * resolves a Request dependency, the scope can be upgraded.
179
+ *
180
+ * @param name The name of the dependency
181
+ * @param scope The scope of the dependency
182
+ */
183
+ trackDependency(name: string, scope: InjectableScope): void;
184
+ }
185
+ //#endregion
72
186
  //#region src/utils/get-injectors.d.mts
73
187
  interface Injectors {
74
188
  asyncInject<T extends ClassTypeWithoutArguments>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
@@ -112,7 +226,7 @@ interface Injectors {
112
226
  optional<T>(token: BoundInjectionToken<T, any>): T | null;
113
227
  optional<T>(token: FactoryInjectionToken<T, any>): T | null;
114
228
  wrapSyncInit(cb: () => any): (injectState?: InjectState) => [any, Promise<any>[], InjectState];
115
- provideFactoryContext(context: FactoryContext | null): FactoryContext | null;
229
+ provideFactoryContext(context: ServiceInitializationContext | null): ServiceInitializationContext | null;
116
230
  }
117
231
  declare function getInjectors(): Injectors;
118
232
  //#endregion
@@ -133,76 +247,12 @@ interface FactoryContext {
133
247
  addDestroyListener: (listener: () => void) => void;
134
248
  }
135
249
  //#endregion
136
- //#region src/token/injection-token.d.mts
137
- type ClassType = new (...args: any[]) => any;
138
- type ClassTypeWithoutArguments = new () => any;
139
- type ClassTypeWithArgument<Arg> = new (arg: Arg) => any;
140
- type ClassTypeWithOptionalArgument<Arg> = new (arg?: Arg) => any;
141
- type ClassTypeWithInstance<T> = new (...args: any[]) => T;
142
- type ClassTypeWithInstanceAndArgument<T, Arg> = new (arg: Arg) => T;
143
- type ClassTypeWithInstanceAndOptionalArgument<T, Arg> = new (arg?: Arg) => T;
144
- type BaseInjectionTokenSchemaType = ZodObject | ZodRecord;
145
- type OptionalInjectionTokenSchemaType = ZodOptional<ZodObject> | ZodOptional<ZodRecord>;
146
- type InjectionTokenSchemaType = BaseInjectionTokenSchemaType | OptionalInjectionTokenSchemaType;
147
- declare class InjectionToken<T, S extends InjectionTokenSchemaType | unknown = unknown, Required extends boolean = (S extends ZodOptional<ZodObject> ? false : S extends ZodOptional<ZodRecord> ? false : S extends ZodObject ? true : S extends ZodRecord ? true : false)> {
148
- readonly name: string | symbol | ClassType;
149
- readonly schema: ZodObject | undefined;
150
- id: `${string}-${string}-${string}-${string}-${string}`;
151
- private formattedName;
152
- constructor(name: string | symbol | ClassType, schema: ZodObject | undefined);
153
- static create<T extends ClassType>(name: T): InjectionToken<InstanceType<T>, undefined>;
154
- static create<T extends ClassType, Schema extends InjectionTokenSchemaType>(name: T, schema: Schema): Schema['_def']['type'] extends 'ZodOptional' ? InjectionToken<InstanceType<T>, Schema, false> : InjectionToken<InstanceType<T>, Schema, true>;
155
- static create<T>(name: string | symbol): InjectionToken<T, undefined>;
156
- static create<T, Schema extends InjectionTokenSchemaType>(name: string | any, schema: Schema): InjectionToken<T, Schema>;
157
- static bound<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, value: z.input<S>): BoundInjectionToken<T, S>;
158
- static factory<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>): FactoryInjectionToken<T, S>;
159
- static refineType<T>(token: BoundInjectionToken<any, any>): BoundInjectionToken<T, any>;
160
- toString(): string;
161
- }
162
- declare class BoundInjectionToken<T, S extends InjectionTokenSchemaType> {
163
- readonly token: InjectionToken<T, S>;
164
- readonly value: z.input<S>;
165
- id: string;
166
- name: string | symbol | ClassType;
167
- schema: InjectionTokenSchemaType;
168
- constructor(token: InjectionToken<T, S>, value: z.input<S>);
169
- toString(): string;
170
- }
171
- declare class FactoryInjectionToken<T, S extends InjectionTokenSchemaType> {
172
- readonly token: InjectionToken<T, S>;
173
- readonly factory: (ctx: FactoryContext) => Promise<z.input<S>>;
174
- value?: z.input<S>;
175
- resolved: boolean;
176
- id: string;
177
- name: string | symbol | ClassType;
178
- schema: InjectionTokenSchemaType;
179
- constructor(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>);
180
- resolve(ctx: FactoryContext): Promise<z.input<S>>;
181
- toString(): string;
182
- }
183
- type AnyInjectableType = ClassType | InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
184
- type InjectionTokenType = InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
185
- //#endregion
186
- //#region src/enums/injectable-scope.enum.d.mts
187
- declare enum InjectableScope {
188
- /**
189
- * Singleton scope: The instance is created once and shared across the application.
190
- */
191
- Singleton = "Singleton",
192
- /**
193
- * Instance scope: A new instance is created for each injection.
194
- */
195
- Transient = "Transient",
196
- /**
197
- * Request scope: The instance is created once per request and shared within that request context.
198
- */
199
- Request = "Request",
250
+ //#region src/interfaces/factory.interface.d.mts
251
+ interface Factorable<T> {
252
+ create(ctx?: FactoryContext): Promise<T> | T;
200
253
  }
201
- //#endregion
202
- //#region src/enums/injectable-type.enum.d.mts
203
- declare enum InjectableType {
204
- Class = "Class",
205
- Factory = "Factory",
254
+ interface FactorableWithArgs<T, A extends InjectionTokenSchemaType> {
255
+ create(ctx?: FactoryContext, ...args: [z.output<A>]): Promise<T> | T;
206
256
  }
207
257
  //#endregion
208
258
  //#region src/token/registry.d.mts
@@ -211,14 +261,17 @@ type FactoryRecord<Instance = any, Schema = any> = {
211
261
  originalToken: InjectionToken<Instance, Schema>;
212
262
  target: ClassType;
213
263
  type: InjectableType;
264
+ priority: number;
214
265
  };
215
266
  declare class Registry {
216
267
  private readonly parent?;
217
268
  private readonly factories;
269
+ private readonly highestPriority;
218
270
  constructor(parent?: Registry | undefined);
219
271
  has(token: InjectionToken<any, any>): boolean;
220
272
  get<Instance, Schema>(token: InjectionToken<Instance, Schema>): FactoryRecord<Instance, Schema>;
221
- set<Instance, Schema>(token: InjectionToken<Instance, Schema>, scope: InjectableScope, target: ClassType, type: InjectableType): void;
273
+ getAll<Instance, Schema>(token: InjectionToken<Instance, Schema>): FactoryRecord<Instance, Schema>[];
274
+ set<Instance, Schema>(token: InjectionToken<Instance, Schema>, scope: InjectableScope, target: ClassType, type: InjectableType, priority?: number): void;
222
275
  delete(token: InjectionToken<any, any>): void;
223
276
  /**
224
277
  * Updates the scope of an already registered factory.
@@ -233,6 +286,52 @@ declare class Registry {
233
286
  }
234
287
  declare const globalRegistry: Registry;
235
288
  //#endregion
289
+ //#region src/internal/core/name-resolver.d.mts
290
+ /**
291
+ * Handles instance name generation with support for requestId and scope.
292
+ *
293
+ * Generates unique instance identifiers based on token, arguments, and scope.
294
+ * Request-scoped services MUST include requestId in their name for proper isolation.
295
+ */
296
+ declare class NameResolver {
297
+ private readonly logger;
298
+ private readonly instanceNameCache;
299
+ constructor(logger?: Console | null);
300
+ /**
301
+ * Generates a unique instance name based on token, arguments, requestId, and scope.
302
+ *
303
+ * Name formats:
304
+ * - Singleton/Transient without args: `${tokenId}`
305
+ * - Singleton/Transient with args: `${tokenId}:${argsHash}`
306
+ * - Request without args: `${tokenId}:requestId=${requestId}`
307
+ * - Request with args: `${tokenId}:requestId=${requestId}:${argsHash}`
308
+ *
309
+ * @param token The injection token
310
+ * @param args Optional arguments
311
+ * @param requestId Optional request ID (required for request-scoped services)
312
+ * @param scope Optional scope (used to determine if requestId should be included)
313
+ * @returns The generated instance name
314
+ */
315
+ generateInstanceName(token: InjectionTokenType, args?: any, requestId?: string, scope?: InjectableScope): string;
316
+ /**
317
+ * Upgrades an existing instance name to include requestId.
318
+ * Preserves any args hash that might already be in the name.
319
+ *
320
+ * Examples:
321
+ * - `TokenName` → `TokenName:requestId=req-123`
322
+ * - `TokenName:abc123` → `TokenName:requestId=req-123:abc123`
323
+ *
324
+ * @param existingName The existing instance name (without requestId)
325
+ * @param requestId The request ID to add
326
+ * @returns The upgraded instance name with requestId
327
+ */
328
+ upgradeInstanceNameToRequest(existingName: string, requestId: string): string;
329
+ /**
330
+ * Formats a single argument value for instance name generation.
331
+ */
332
+ formatArgValue(value: any): string;
333
+ }
334
+ //#endregion
236
335
  //#region src/errors/di-error.d.mts
237
336
  declare enum DIErrorCode {
238
337
  FactoryNotFound = "FactoryNotFound",
@@ -240,6 +339,14 @@ declare enum DIErrorCode {
240
339
  InstanceNotFound = "InstanceNotFound",
241
340
  InstanceDestroying = "InstanceDestroying",
242
341
  CircularDependency = "CircularDependency",
342
+ TokenValidationError = "TokenValidationError",
343
+ TokenSchemaRequiredError = "TokenSchemaRequiredError",
344
+ ClassNotInjectable = "ClassNotInjectable",
345
+ ScopeMismatchError = "ScopeMismatchError",
346
+ PriorityConflictError = "PriorityConflictError",
347
+ StorageError = "StorageError",
348
+ InitializationError = "InitializationError",
349
+ DependencyResolutionError = "DependencyResolutionError",
243
350
  UnknownError = "UnknownError",
244
351
  }
245
352
  declare class DIError extends Error {
@@ -253,6 +360,14 @@ declare class DIError extends Error {
253
360
  static instanceDestroying(name: string): DIError;
254
361
  static unknown(message: string | Error, context?: Record<string, unknown>): DIError;
255
362
  static circularDependency(cycle: string[]): DIError;
363
+ static tokenValidationError(message: string, schema: InjectionTokenSchemaType | undefined, value: unknown): DIError;
364
+ static tokenSchemaRequiredError(token: string | symbol | unknown): DIError;
365
+ static classNotInjectable(className: string): DIError;
366
+ static scopeMismatchError(token: string | symbol | unknown, expectedScope: string, actualScope: string): DIError;
367
+ static priorityConflictError(token: string | symbol | unknown, records: FactoryRecord[]): DIError;
368
+ static storageError(message: string, operation: string, instanceName?: string): DIError;
369
+ static initializationError(serviceName: string, error: Error | string): DIError;
370
+ static dependencyResolutionError(serviceName: string, dependencyName: string, error: Error | string): DIError;
256
371
  }
257
372
  //#endregion
258
373
  //#region src/internal/holder/instance-holder.d.mts
@@ -269,8 +384,6 @@ declare enum InstanceStatus {
269
384
  /** Instance creation failed with an error */
270
385
  Error = "error",
271
386
  }
272
- /** Callback function for instance effects */
273
- type InstanceEffect = () => void;
274
387
  /** Callback function for instance destruction listeners */
275
388
  type InstanceDestroyListener = () => void | Promise<void>;
276
389
  /**
@@ -365,8 +478,7 @@ type HolderGetResult<T = unknown> = [undefined, InstanceHolder<T>] | [DIError, I
365
478
  * Interface for abstracting holder storage operations.
366
479
  *
367
480
  * Enables unified instance resolution logic regardless of where
368
- * holders are stored (singleton manager, request context, etc.).
369
- * This is the key abstraction for the Storage Strategy pattern.
481
+ * holders are stored. This is the key abstraction for the unified storage pattern.
370
482
  */
371
483
  interface IHolderStorage {
372
484
  /**
@@ -435,271 +547,296 @@ interface IHolderStorage {
435
547
  * @returns Array of instance names that have this instance as a dependency
436
548
  */
437
549
  findDependents(instanceName: string): string[];
550
+ /**
551
+ * Updates dependency references when instance names change.
552
+ * Used during scope upgrades when instance names are regenerated with requestId.
553
+ *
554
+ * @param oldName The old instance name
555
+ * @param newName The new instance name
556
+ */
557
+ updateDependencyReference(oldName: string, newName: string): void;
438
558
  }
439
559
  //#endregion
440
- //#region src/internal/holder/base-holder-manager.d.mts
560
+ //#region src/internal/lifecycle/lifecycle-event-bus.d.mts
441
561
  /**
442
- * Result type for waitForHolderReady.
443
- * Returns either [undefined, holder] on success or [error] on failure.
562
+ * Event bus for service lifecycle events (create, destroy, etc.).
563
+ *
564
+ * Enables loose coupling between services by allowing them to subscribe
565
+ * to lifecycle events of their dependencies without direct references.
566
+ * Used primarily for invalidation cascading.
444
567
  */
445
- type HolderReadyResult<T> = [undefined, InstanceHolder<T>] | [DIError];
568
+ declare class LifecycleEventBus {
569
+ private readonly logger;
570
+ private listeners;
571
+ constructor(logger?: Console | null);
572
+ on<Event extends string | `pre:${string}` | `post:${string}`>(ns: string, event: Event, listener: (event: Event) => void): () => void;
573
+ emit(key: string, event: string): Promise<PromiseSettledResult<any>[] | undefined>;
574
+ }
575
+ //#endregion
576
+ //#region src/internal/core/service-invalidator.d.mts
577
+ interface ClearAllOptions {
578
+ /** Whether to wait for all services to settle before starting (default: true) */
579
+ waitForSettlement?: boolean;
580
+ }
581
+ interface InvalidationOptions {
582
+ /** Whether to emit events after invalidation (default: true) */
583
+ emitEvents?: boolean;
584
+ /** Custom event emitter function */
585
+ onInvalidated?: (instanceName: string) => Promise<void>;
586
+ /** Whether to cascade invalidation to dependents (default: false - events handle it) */
587
+ cascade?: boolean;
588
+ }
446
589
  /**
447
- * Abstract base class providing common functionality for managing InstanceHolder objects.
590
+ * Manages graceful service cleanup with event-based invalidation.
448
591
  *
449
- * Provides shared patterns for holder storage, creation, and lifecycle management
450
- * used by both singleton (HolderManager) and request-scoped (RequestContext) managers.
592
+ * Uses event subscriptions instead of manual dependent finding.
593
+ * When a service is created, it subscribes to destroy events of its dependencies.
594
+ * When a dependency is destroyed, the event automatically invalidates dependents.
451
595
  */
452
- declare abstract class BaseHolderManager {
453
- protected readonly logger: Console | null;
454
- protected readonly _holders: Map<string, InstanceHolder>;
596
+ declare class ServiceInvalidator {
597
+ private readonly eventBus;
598
+ private readonly logger;
599
+ constructor(eventBus: LifecycleEventBus | null, logger?: Console | null);
455
600
  /**
456
- * Reverse dependency index: maps a dependency name to the set of holder names that depend on it.
457
- * This allows O(1) lookup of dependents instead of O(n) iteration.
601
+ * Invalidates a service using a specific storage.
602
+ * Event-based invalidation means dependents are automatically invalidated
603
+ * via destroy event subscriptions - no need to manually find dependents.
604
+ *
605
+ * @param service The instance name to invalidate
606
+ * @param storage The storage to use for this invalidation
607
+ * @param options Additional options for invalidation behavior
458
608
  */
459
- protected readonly _dependents: Map<string, Set<string>>;
460
- constructor(logger?: Console | null);
609
+ invalidateWithStorage(service: string, storage: IHolderStorage, options?: InvalidationOptions): Promise<void>;
461
610
  /**
462
- * Protected getter for accessing the holders map from subclasses.
611
+ * Sets up destroy event subscriptions for a service's dependencies.
612
+ * Called when a service is successfully instantiated.
613
+ *
614
+ * @param serviceName The name of the service
615
+ * @param dependencies The set of dependency names
616
+ * @param storage The storage to use for invalidation
617
+ * @param holder The holder for the service (to add unsubscribe to destroy listeners)
463
618
  */
464
- protected get holders(): Map<string, InstanceHolder>;
619
+ setupDependencySubscriptions(serviceName: string, dependencies: Set<string>, storage: IHolderStorage, holder: InstanceHolder): void;
465
620
  /**
466
- * Abstract method to get a holder by name. Each implementation defines its own return type
467
- * based on their specific error handling and validation needs.
621
+ * Gracefully clears all services in a specific storage.
622
+ * This allows clearing request-scoped services using a RequestStorage.
468
623
  */
469
- abstract get(name: string): any;
624
+ clearAllWithStorage(storage: IHolderStorage, options?: ClearAllOptions): Promise<void>;
470
625
  /**
471
- * Abstract method to set a holder by name. Each implementation may have different validation logic.
626
+ * Waits for all services in a specific storage to settle.
472
627
  */
473
- abstract set(name: string, holder: InstanceHolder): void;
628
+ readyWithStorage(storage: IHolderStorage): Promise<void>;
474
629
  /**
475
- * Abstract method to check if a holder exists. Each implementation may have different validation logic.
630
+ * Invalidates a single holder using a specific storage.
476
631
  */
477
- abstract has(name: string): any;
632
+ private invalidateHolderWithStorage;
478
633
  /**
479
- * Deletes a holder by name and cleans up the reverse dependency index.
480
- * @param name The name of the holder to delete
481
- * @returns true if the holder was deleted, false if it didn't exist
634
+ * Common invalidation logic for holders based on their status.
482
635
  */
483
- delete(name: string): boolean;
636
+ private invalidateHolderByStatus;
484
637
  /**
485
- * Registers a holder's dependencies in the reverse index.
486
- * Call this after creating a holder with dependencies.
487
- * @param holderName The name of the holder that has dependencies
488
- * @param deps The set of dependency names
638
+ * Destroys a holder using a specific storage.
489
639
  */
490
- registerDependencies(holderName: string, deps: Set<string>): void;
640
+ private destroyHolderWithStorage;
491
641
  /**
492
- * Removes a holder from the reverse dependency index.
493
- * @param holderName The name of the holder to remove
494
- * @param deps The set of dependency names to clean up
642
+ * Waits for a holder to settle (either created, destroyed, or error state).
495
643
  */
496
- protected removeFromDependentsIndex(holderName: string, deps: Set<string>): void;
644
+ private waitForHolderToSettle;
497
645
  /**
498
- * Gets all holder names that depend on the given instance name.
499
- * O(1) lookup using the reverse dependency index.
500
- * @param instanceName The instance name to find dependents for
501
- * @returns Array of holder names that depend on this instance
646
+ * Emits events to listeners for instance lifecycle events.
502
647
  */
503
- getDependents(instanceName: string): string[];
504
- /**
505
- * Filters holders based on a predicate function.
506
- * @param predicate Function to test each holder
507
- * @returns A new Map containing only the holders that match the predicate
508
- * @deprecated Use forEachHolder() for iteration to avoid allocations
509
- */
510
- filter(predicate: (value: InstanceHolder<any>, key: string) => boolean): Map<string, InstanceHolder>;
511
- /**
512
- * Iterates over holders with a callback. More efficient than filter() as it
513
- * avoids creating intermediate arrays and Maps.
514
- * @param callback Function called for each holder with (holder, name)
515
- */
516
- forEachHolder(callback: (holder: InstanceHolder<any>, name: string) => void): void;
517
- /**
518
- * Finds the first holder matching a predicate. More efficient than filter()
519
- * when only one result is needed.
520
- * @param predicate Function to test each holder
521
- * @returns The first matching holder or undefined
522
- */
523
- findHolder(predicate: (holder: InstanceHolder<any>, name: string) => boolean): InstanceHolder | undefined;
524
- /**
525
- * Clears all holders from this manager and the reverse dependency index.
526
- */
527
- clear(): void;
528
- /**
529
- * Gets the number of holders currently managed.
530
- */
531
- size(): number;
532
- /**
533
- * Creates a new holder with Creating status and a deferred creation promise.
534
- * This is useful for creating placeholder holders that can be fulfilled later.
535
- * @param name The name of the instance
536
- * @param type The injectable type
537
- * @param scope The injectable scope
538
- * @param deps Optional set of dependencies
539
- * @returns A tuple containing the deferred promise and the holder
540
- */
541
- createCreatingHolder<Instance>(name: string, type: InjectableType, scope: InjectableScope, deps?: Set<string>): [ReturnType<typeof Promise.withResolvers<[undefined, Instance]>>, InstanceHolder<Instance>];
542
- /**
543
- * Creates a new holder with Created status and an actual instance.
544
- * This is useful for creating holders that already have their instance ready.
545
- * @param name The name of the instance
546
- * @param instance The actual instance to store
547
- * @param type The injectable type
548
- * @param scope The injectable scope
549
- * @param deps Optional set of dependencies
550
- * @returns The created holder
551
- */
552
- protected createCreatedHolder<Instance>(name: string, instance: Instance, type: InjectableType, scope: InjectableScope, deps?: Set<string>): InstanceHolder<Instance>;
648
+ private emitInstanceEvent;
649
+ }
650
+ //#endregion
651
+ //#region src/internal/core/token-resolver.d.mts
652
+ /**
653
+ * Handles token validation and resolution.
654
+ *
655
+ * Focuses on token validation, normalization, and argument validation.
656
+ * Name generation is handled by NameResolver.
657
+ */
658
+ declare class TokenResolver {
659
+ private readonly logger;
660
+ constructor(logger?: Console | null);
553
661
  /**
554
- * Gets all holder names currently managed.
662
+ * Normalizes a token to an InjectionToken.
663
+ * Handles class constructors by getting their injectable token.
664
+ *
665
+ * @param token A class constructor, InjectionToken, BoundInjectionToken, or FactoryInjectionToken
666
+ * @returns The normalized InjectionTokenType
555
667
  */
556
- getAllNames(): string[];
668
+ normalizeToken(token: AnyInjectableType): InjectionTokenType;
557
669
  /**
558
- * Gets all holders currently managed.
670
+ * Gets the underlying "real" token from wrapped tokens.
671
+ * For BoundInjectionToken and FactoryInjectionToken, returns the wrapped token.
672
+ * For other tokens, returns the token itself.
673
+ *
674
+ * @param token The token to unwrap
675
+ * @returns The underlying InjectionToken
559
676
  */
560
- getAllHolders(): InstanceHolder[];
677
+ getRealToken<T = unknown>(token: InjectionTokenType): InjectionToken<T>;
561
678
  /**
562
- * Checks if this manager has any holders.
679
+ * Convenience method that normalizes a token and then gets the real token.
680
+ * Useful for checking registry entries where you need the actual registered token.
681
+ *
682
+ * @param token Any injectable type
683
+ * @returns The underlying InjectionToken
563
684
  */
564
- isEmpty(): boolean;
685
+ getRegistryToken<T = unknown>(token: AnyInjectableType): InjectionToken<T>;
565
686
  /**
566
- * Waits for a holder to be ready and returns the appropriate result.
567
- * This is a shared utility used by both singleton and request-scoped resolution.
687
+ * Validates and resolves token arguments, handling factory token resolution and validation.
568
688
  *
569
- * @param holder The holder to wait for
570
- * @param waiterHolder Optional holder that is doing the waiting (for circular dependency detection)
571
- * @param getHolder Optional function to retrieve holders by name (required if waiterHolder is provided)
572
- * @returns A promise that resolves with [undefined, holder] on success or [DIError] on failure
689
+ * @param token The token to validate
690
+ * @param args Optional arguments
691
+ * @returns [error, { actualToken, validatedArgs }]
573
692
  */
574
- static waitForHolderReady<T>(holder: InstanceHolder<T>, waiterHolder?: InstanceHolder, getHolder?: (name: string) => InstanceHolder | undefined): Promise<HolderReadyResult<T>>;
693
+ validateAndResolveTokenArgs(token: AnyInjectableType, args?: any): [DIError | undefined, {
694
+ actualToken: InjectionTokenType;
695
+ validatedArgs?: any;
696
+ }];
575
697
  }
576
698
  //#endregion
577
- //#region src/internal/context/request-context.d.mts
699
+ //#region src/internal/holder/unified-storage.d.mts
578
700
  /**
579
- * Interface for request context that manages pre-prepared instances for a specific request.
701
+ * Unified storage implementation that works the same way regardless of scope.
702
+ * Replaces RequestContext, HolderManager, SingletonStorage, RequestStorage.
580
703
  *
581
- * Provides isolated storage for request-scoped services, enabling efficient
582
- * instantiation and cleanup within the lifecycle of a single request.
704
+ * Scope is just metadata - storage operations are identical for all scopes.
705
+ * Different storage instances are just isolated storage spaces.
583
706
  */
584
- interface RequestContext {
585
- /**
586
- * Unique identifier for this request context.
587
- */
588
- readonly requestId: string;
707
+ declare class UnifiedStorage implements IHolderStorage {
708
+ readonly scope: InjectableScope;
709
+ private readonly holders;
589
710
  /**
590
- * Instance holders for request-scoped services.
711
+ * Reverse dependency index: maps a dependency name to the set of holder names that depend on it.
712
+ * This allows O(1) lookup of dependents instead of O(n) iteration.
591
713
  */
592
- readonly holders: Map<string, InstanceHolder>;
714
+ private readonly dependents;
715
+ constructor(scope?: InjectableScope);
716
+ get<T = unknown>(instanceName: string): HolderGetResult<T>;
717
+ set(instanceName: string, holder: InstanceHolder): void;
718
+ delete(instanceName: string): boolean;
719
+ createHolder<T>(instanceName: string, type: InjectableType, deps: Set<string>): [ReturnType<typeof Promise.withResolvers<[undefined, T]>>, InstanceHolder<T>];
720
+ storeInstance(instanceName: string, instance: unknown): void;
721
+ handles(scope: InjectableScope): boolean;
722
+ getAllNames(): string[];
723
+ forEach(callback: (name: string, holder: InstanceHolder) => void): void;
724
+ findByInstance(instance: unknown): InstanceHolder | null;
725
+ findDependents(instanceName: string): string[];
593
726
  /**
594
- * Priority for resolution in FactoryContext.inject method.
595
- * Higher values take precedence.
727
+ * Updates dependency references when instance names change.
728
+ * Used during scope upgrades when instance names are regenerated with requestId.
729
+ *
730
+ * @param oldName The old instance name
731
+ * @param newName The new instance name
596
732
  */
597
- readonly priority: number;
733
+ updateDependencyReference(oldName: string, newName: string): void;
598
734
  /**
599
- * Request-specific metadata that can be used during instantiation.
735
+ * Registers a holder's dependencies in the reverse index.
600
736
  */
601
- readonly metadata: Map<string, any>;
737
+ private registerDependencies;
602
738
  /**
603
- * Timestamp when this context was created.
739
+ * Removes a holder from the reverse dependency index.
604
740
  */
605
- readonly createdAt: number;
741
+ private removeFromDependentsIndex;
742
+ }
743
+ //#endregion
744
+ //#region src/container/abstract-container.d.mts
745
+ /**
746
+ * Abstract base class for dependency injection containers.
747
+ *
748
+ * Provides shared implementation for common container operations.
749
+ * Both Container and ScopedContainer extend this class.
750
+ */
751
+ declare abstract class AbstractContainer implements IContainer {
606
752
  /**
607
- * Adds a pre-prepared instance to this context.
753
+ * The default scope used when adding instances without explicit registration.
608
754
  */
609
- addInstance(instanceName: string, instance: any, holder: InstanceHolder): void;
755
+ protected abstract readonly defaultScope: InjectableScope;
610
756
  /**
611
- * Adds a pre-prepared instance to this context.
757
+ * The request ID for scoped containers, undefined for root container.
612
758
  */
613
- addInstance(token: InjectionToken<any, undefined>, instance: any): void;
759
+ protected abstract readonly requestId: string | undefined;
614
760
  /**
615
- * Gets an instance holder from this context.
761
+ * Gets the storage for this container.
616
762
  */
617
- get(instanceName: string): InstanceHolder | undefined;
763
+ abstract getStorage(): UnifiedStorage;
618
764
  /**
619
- * Sets an instance holder by name.
765
+ * Gets the registry for this container.
620
766
  */
621
- set(instanceName: string, holder: InstanceHolder): void;
767
+ protected abstract getRegistry(): Registry;
622
768
  /**
623
- * Checks if this context has a pre-prepared instance.
769
+ * Gets the token resolver.
624
770
  */
625
- has(instanceName: string): boolean;
771
+ protected abstract getTokenResolver(): TokenResolver;
626
772
  /**
627
- * Clears all instances and holders from this context.
773
+ * Gets the name resolver.
628
774
  */
629
- clear(): void;
775
+ protected abstract getNameResolver(): NameResolver;
630
776
  /**
631
- * Gets metadata value by key.
777
+ * Gets the service invalidator.
632
778
  */
633
- getMetadata(key: string): any | undefined;
779
+ protected abstract getServiceInvalidator(): ServiceInvalidator;
634
780
  /**
635
- * Sets metadata value by key.
636
- */
637
- setMetadata(key: string, value: any): void;
638
- /**
639
- * Filters holders based on a predicate function.
781
+ * Gets an instance from the container.
640
782
  */
641
- filter(predicate: (value: InstanceHolder<any>, key: string) => boolean): Map<string, InstanceHolder>;
783
+ abstract get<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
784
+ abstract get<T extends ClassTypeWithArgument<R>, R>(token: T, args: R): Promise<InstanceType<T>>;
785
+ abstract get<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
786
+ abstract get<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? Promise<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
787
+ abstract get<T>(token: InjectionToken<T, undefined>): Promise<T>;
788
+ abstract get<T>(token: BoundInjectionToken<T, any>): Promise<T>;
789
+ abstract get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
642
790
  /**
643
- * Deletes a holder by name.
791
+ * Invalidates a service and its dependencies.
644
792
  */
645
- delete(name: string): boolean;
793
+ abstract invalidate(service: unknown): Promise<void>;
646
794
  /**
647
- * Gets the number of holders currently managed.
795
+ * Disposes the container and cleans up all resources.
648
796
  */
649
- size(): number;
797
+ abstract dispose(): Promise<void>;
650
798
  /**
651
- * Checks if this manager has any holders.
799
+ * Calculates the instance name for a given token and optional arguments.
800
+ *
801
+ * @internal
802
+ * @param token The class type, InjectionToken, BoundInjectionToken, or FactoryInjectionToken
803
+ * @param args Optional arguments (ignored for BoundInjectionToken which uses its bound value)
804
+ * @returns The calculated instance name string, or null if the token is a FactoryInjectionToken that is not yet resolved
652
805
  */
653
- isEmpty(): boolean;
806
+ calculateInstanceName(token: ClassType | InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>, args?: unknown): string | null;
654
807
  /**
655
- * Registers a holder's dependencies in the reverse index.
808
+ * Checks if a service is registered in the container.
656
809
  */
657
- registerDependencies(holderName: string, deps: Set<string>): void;
810
+ isRegistered(token: any): boolean;
658
811
  /**
659
- * Gets all holder names that depend on the given instance name.
660
- * O(1) lookup using the reverse dependency index.
812
+ * Waits for all pending operations to complete.
661
813
  */
662
- getDependents(instanceName: string): string[];
663
- }
664
- /** @deprecated Use RequestContext instead */
665
- type RequestContextHolder = RequestContext;
666
- /**
667
- * Default implementation of RequestContext.
668
- *
669
- * Extends BaseHolderManager to provide holder management functionality
670
- * with request-specific metadata and lifecycle support.
671
- */
672
- declare class DefaultRequestContext extends BaseHolderManager implements RequestContext {
673
- readonly requestId: string;
674
- readonly priority: number;
675
- readonly metadata: Map<string, any>;
676
- readonly createdAt: number;
677
- constructor(requestId: string, priority?: number, initialMetadata?: Record<string, any>);
814
+ ready(): Promise<void>;
678
815
  /**
679
- * Public getter for holders to maintain interface compatibility.
816
+ * @internal
817
+ * Attempts to get an instance synchronously if it already exists.
680
818
  */
681
- get holders(): Map<string, InstanceHolder>;
819
+ tryGetSync<T>(token: any, args?: any): T | null;
682
820
  /**
683
- * Gets a holder by name. For RequestContext, this is a simple lookup.
821
+ * @internal
822
+ * Internal method for getting instances synchronously with configurable storage.
684
823
  */
685
- get(name: string): InstanceHolder | undefined;
824
+ protected tryGetSyncFromStorage<T>(token: any, args: any, storage: UnifiedStorage, requestId?: string): T | null;
686
825
  /**
687
- * Sets a holder by name.
826
+ * Adds an instance to the container.
827
+ * Accepts class types, InjectionTokens, and BoundInjectionTokens.
828
+ * Rejects InjectionTokens with required schemas (use BoundInjectionToken instead).
829
+ *
830
+ * @param token The class type, InjectionToken, or BoundInjectionToken to register the instance for
831
+ * @param instance The instance to store
688
832
  */
689
- set(name: string, holder: InstanceHolder): void;
833
+ addInstance<T>(token: ClassType | InjectionToken<T, any> | BoundInjectionToken<T, any>, instance: T): void;
690
834
  /**
691
- * Checks if a holder exists by name.
835
+ * @internal
836
+ * Internal method for adding instances with configurable scope and storage.
692
837
  */
693
- has(name: string): boolean;
694
- addInstance(instanceName: string | InjectionToken<any, undefined>, instance: any, holder?: InstanceHolder): void;
695
- clear(): void;
696
- getMetadata(key: string): any | undefined;
697
- setMetadata(key: string, value: any): void;
838
+ protected addInstanceToStorage<T>(token: ClassType | InjectionToken<T, any> | BoundInjectionToken<T, any>, instance: T, storage: UnifiedStorage, scope: InjectableScope, requestId?: string): void;
698
839
  }
699
- /**
700
- * Creates a new request context with the given parameters.
701
- */
702
- declare function createRequestContext(requestId: string, priority?: number, initialMetadata?: Record<string, any>): RequestContext;
703
840
  //#endregion
704
841
  //#region src/container/scoped-container.d.mts
705
842
  /**
@@ -710,23 +847,20 @@ declare function createRequestContext(requestId: string, priority?: number, init
710
847
  * This design eliminates race conditions that can occur with async operations
711
848
  * when multiple requests are processed concurrently.
712
849
  */
713
- declare class ScopedContainer implements IContainer {
850
+ declare class ScopedContainer extends AbstractContainer {
714
851
  private readonly parent;
715
852
  private readonly registry;
716
853
  readonly requestId: string;
717
- private readonly requestContextHolder;
718
- private readonly holderStorage;
854
+ protected readonly defaultScope = InjectableScope.Request;
855
+ private readonly storage;
719
856
  private disposed;
720
- constructor(parent: Container, registry: Registry, requestId: string, metadata?: Record<string, any>, priority?: number);
721
- /**
722
- * Gets the request context holder for this scoped container.
723
- */
724
- getRequestContextHolder(): RequestContext;
725
- /**
726
- * Gets the holder storage for this scoped container.
727
- * Used by InstanceResolver for request-scoped resolution.
728
- */
729
- getHolderStorage(): IHolderStorage;
857
+ private readonly metadata;
858
+ constructor(parent: Container, registry: Registry, requestId: string, metadata?: Record<string, any>);
859
+ getStorage(): UnifiedStorage;
860
+ protected getRegistry(): Registry;
861
+ protected getTokenResolver(): TokenResolver;
862
+ protected getNameResolver(): NameResolver;
863
+ protected getServiceInvalidator(): ServiceInvalidator;
730
864
  /**
731
865
  * Gets the request ID for this scoped container.
732
866
  */
@@ -743,13 +877,9 @@ declare class ScopedContainer implements IContainer {
743
877
  * Sets metadata on the request context.
744
878
  */
745
879
  setMetadata(key: string, value: any): void;
746
- /**
747
- * Adds a pre-prepared instance to the request context.
748
- */
749
- addInstance(token: InjectionToken<any, undefined>, instance: any): void;
750
880
  /**
751
881
  * Gets an instance from the container.
752
- * Request-scoped services are resolved from this container's context.
882
+ * Request-scoped services are resolved from this container's storage.
753
883
  * All other services are delegated to the parent container.
754
884
  */
755
885
  get<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
@@ -761,354 +891,251 @@ declare class ScopedContainer implements IContainer {
761
891
  get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
762
892
  /**
763
893
  * Invalidates a service and its dependencies.
764
- * For request-scoped services, invalidation is handled within this context.
765
894
  */
766
895
  invalidate(service: unknown): Promise<void>;
767
896
  /**
768
- * Checks if a service is registered.
769
- */
770
- isRegistered(token: any): boolean;
771
- /**
772
- * Disposes this scoped container and cleans up all request-scoped instances.
773
- * This is an alias for endRequest() for IContainer compatibility.
897
+ * Disposes the container and cleans up all resources.
898
+ * Alias for endRequest().
774
899
  */
775
900
  dispose(): Promise<void>;
776
- /**
777
- * Ends the request and cleans up all request-scoped instances.
778
- * Uses the invalidation system to properly cascade to dependent singletons.
779
- */
780
- endRequest(): Promise<void>;
781
- /**
782
- * Waits for all pending operations to complete.
783
- */
784
- ready(): Promise<void>;
785
901
  /**
786
902
  * @internal
787
- * Attempts to get an instance synchronously if it already exists and is ready.
788
- * For request-scoped services, checks this container's context first.
789
- * For other services, delegates to the parent container.
790
- *
791
- * Returns null if the instance doesn't exist or is not yet ready (still creating).
903
+ * Attempts to get an instance synchronously if it already exists.
904
+ * Checks request storage first, then delegates to parent.
792
905
  */
793
906
  tryGetSync<T>(token: any, args?: any): T | null;
794
907
  /**
795
- * Checks if a token is for a request-scoped service.
796
- */
797
- private isRequestScoped;
798
- /**
799
- * Resolves a request-scoped service from this container's context.
800
- * Uses locking to prevent duplicate initialization during concurrent resolution.
801
- */
802
- private resolveRequestScoped;
803
- /**
804
- * Stores an instance in the request context.
805
- * Called by Container during request-scoped service resolution.
806
- */
807
- storeRequestInstance(instanceName: string, instance: any, holder: InstanceHolder): void;
808
- /**
809
- * Gets an existing instance from the request context.
810
- * Called by Container during resolution to check for existing instances.
908
+ * Adds an instance to the container.
909
+ * Overrides base class to check disposed state.
811
910
  */
812
- getRequestInstance(instanceName: string): InstanceHolder | undefined;
911
+ addInstance<T>(token: ClassType | InjectionToken<T, any> | BoundInjectionToken<T, any>, instance: T): void;
813
912
  /**
814
- * Generates a prefixed event name for request-scoped services.
815
- * Format: {requestId}:{instanceName}
913
+ * Ends the request and cleans up all request-scoped services.
816
914
  */
817
- getPrefixedEventName(instanceName: string): string;
818
- }
819
- //#endregion
820
- //#region src/internal/lifecycle/lifecycle-event-bus.d.mts
821
- /**
822
- * Event bus for service lifecycle events (create, destroy, etc.).
823
- *
824
- * Enables loose coupling between services by allowing them to subscribe
825
- * to lifecycle events of their dependencies without direct references.
826
- * Used primarily for invalidation cascading.
827
- */
828
- declare class LifecycleEventBus {
829
- private readonly logger;
830
- private listeners;
831
- constructor(logger?: Console | null);
832
- on<Event extends string | `pre:${string}` | `post:${string}`>(ns: string, event: Event, listener: (event: Event) => void): () => void;
833
- emit(key: string, event: string): Promise<PromiseSettledResult<any>[] | undefined>;
915
+ endRequest(): Promise<void>;
834
916
  }
835
917
  //#endregion
836
- //#region src/internal/holder/holder-manager.d.mts
918
+ //#region src/internal/core/scope-tracker.d.mts
837
919
  /**
838
- * Manages the storage and retrieval of singleton instance holders.
920
+ * Component for tracking and handling scope upgrades.
839
921
  *
840
- * Provides CRUD operations and filtering for the holder map.
841
- * Handles holder state validation (destroying, error states) on retrieval.
922
+ * Detects when a Singleton service needs to be upgraded to Request scope
923
+ * and coordinates the scope upgrade process atomically.
842
924
  */
843
- declare class HolderManager extends BaseHolderManager {
844
- constructor(logger?: Console | null);
845
- get(name: string): [DIError, InstanceHolder] | [DIError] | [undefined, InstanceHolder];
846
- set(name: string, holder: InstanceHolder): void;
847
- has(name: string): [DIError] | [undefined, boolean];
848
- /**
849
- * Creates a new holder with Created status and stores it.
850
- * This is useful for creating holders that already have their instance ready.
851
- * @param name The name of the instance
852
- * @param instance The actual instance to store
853
- * @param type The injectable type
854
- * @param scope The injectable scope
855
- * @param deps Optional set of dependencies
856
- * @returns The created holder
857
- */
858
- storeCreatedHolder<Instance>(name: string, instance: Instance, type: InjectableType, scope: InjectableScope, deps?: Set<string>): InstanceHolder<Instance>;
859
- }
860
- //#endregion
861
- //#region src/internal/core/invalidator.d.mts
862
- interface ClearAllOptions {
863
- /** Maximum number of invalidation rounds to prevent infinite loops (default: 10) */
864
- maxRounds?: number;
865
- /** Whether to wait for all services to settle before starting (default: true) */
866
- waitForSettlement?: boolean;
867
- }
868
- interface InvalidationOptions {
869
- /** Whether to emit events after invalidation (default: true for singletons) */
870
- emitEvents?: boolean;
871
- /** Custom event emitter function */
872
- onInvalidated?: (instanceName: string) => Promise<void>;
873
- /** Whether to cascade invalidation to dependents (default: true) */
874
- cascade?: boolean;
875
- /** Internal: tracks services being invalidated in the current call chain to prevent circular loops */
876
- _invalidating?: Set<string>;
877
- }
878
- /**
879
- * Manages graceful service cleanup with dependency-aware invalidation.
880
- *
881
- * Ensures services are destroyed in the correct order based on their dependencies.
882
- * Works with any IHolderStorage implementation, enabling unified invalidation
883
- * for both singleton and request-scoped services.
884
- */
885
- declare class Invalidator {
886
- private readonly eventBus;
925
+ declare class ScopeTracker {
926
+ private readonly registry;
927
+ private readonly nameResolver;
887
928
  private readonly logger;
888
- private readonly storage;
889
- constructor(manager: HolderManager, eventBus: LifecycleEventBus | null, logger?: Console | null);
929
+ constructor(registry: Registry, nameResolver: NameResolver, logger?: Console | null);
890
930
  /**
891
- * Invalidates a service and all its dependencies.
892
- * Works with the configured storage (singleton by default).
893
- */
894
- invalidate(service: string, round?: number): Promise<any>;
895
- /**
896
- * Invalidates a service using a specific storage.
897
- * This allows request-scoped invalidation using a RequestStorage.
931
+ * Checks if a dependency requires scope upgrade and performs it if needed.
932
+ * Called during service resolution when a dependency is resolved.
898
933
  *
899
- * @param service The instance name to invalidate
900
- * @param storage The storage to use for this invalidation
901
- * @param round Current invalidation round (for recursion limiting)
902
- * @param options Additional options for invalidation behavior
903
- */
904
- invalidateWithStorage(service: string, storage: IHolderStorage, round?: number, options?: InvalidationOptions): Promise<void>;
905
- /**
906
- * Gracefully clears all services using invalidation logic.
907
- * This method respects service dependencies and ensures proper cleanup order.
908
- * Services that depend on others will be invalidated first, then their dependencies.
909
- */
910
- clearAll(options?: ClearAllOptions): Promise<void>;
911
- /**
912
- * Gracefully clears all services in a specific storage.
913
- * This allows clearing request-scoped services using a RequestStorage.
914
- */
915
- clearAllWithStorage(storage: IHolderStorage, options?: ClearAllOptions): Promise<void>;
916
- /**
917
- * Waits for all services to settle (either created, destroyed, or error state).
918
- */
919
- ready(): Promise<void>;
920
- /**
921
- * Waits for all services in a specific storage to settle.
922
- */
923
- readyWithStorage(storage: IHolderStorage): Promise<void>;
924
- /**
925
- * Invalidates a single holder using a specific storage.
926
- */
927
- private invalidateHolderWithStorage;
928
- /**
929
- * Common invalidation logic for holders based on their status.
930
- */
931
- private invalidateHolderByStatus;
932
- /**
933
- * Destroys a holder using a specific storage.
934
+ * @param currentServiceName - Name of the service being created
935
+ * @param currentServiceScope - Current scope of the service being created
936
+ * @param dependencyName - Name of the dependency being resolved
937
+ * @param dependencyScope - Scope of the dependency
938
+ * @param dependencyToken - Token of the dependency
939
+ * @param singletonStorage - Singleton storage instance
940
+ * @param requestStorage - Request storage instance (if in request context)
941
+ * @param requestId - Request ID (if in request context)
942
+ * @returns [needsUpgrade: boolean, newName?: string] - whether upgrade occurred and new name
943
+ */
944
+ checkAndUpgradeScope(currentServiceName: string, currentServiceScope: InjectableScope, dependencyName: string, dependencyScope: InjectableScope, dependencyToken: InjectionToken<any, any>, singletonStorage: IHolderStorage, requestStorage?: IHolderStorage, requestId?: string): [boolean, string?];
945
+ /**
946
+ * Performs the actual scope upgrade from Singleton to Request.
947
+ * This is the core migration logic.
948
+ *
949
+ * @param serviceName - Current service name (without requestId)
950
+ * @param token - Service injection token
951
+ * @param singletonStorage - Source storage
952
+ * @param requestStorage - Target storage
953
+ * @param requestId - Request ID to include in new name
954
+ * @returns [success: boolean, newName?: string, error?: DIError]
934
955
  */
935
- private destroyHolderWithStorage;
956
+ upgradeScopeToRequest(serviceName: string, token: InjectionToken<any, any>, singletonStorage: IHolderStorage, requestStorage: IHolderStorage, requestId: string): Promise<[boolean, string?, DIError?]>;
936
957
  /**
937
- * Waits for a holder to settle (either created, destroyed, or error state).
958
+ * Synchronous part of scope upgrade - handles immediate updates.
959
+ * Async operations (like waiting for holder creation) should be done separately.
938
960
  */
939
- private waitForHolderToSettle;
961
+ private upgradeScopeToRequestSync;
940
962
  /**
941
- * Clears services with dependency awareness for a specific storage.
963
+ * Updates all parent dependencies to reference the new service name.
964
+ *
965
+ * @param oldName - Original service name
966
+ * @param newName - New service name with requestId
967
+ * @param singletonStorage - Singleton storage to check
968
+ * @param requestStorage - Request storage to check
942
969
  */
943
- private clearServicesWithDependencyAwarenessForStorage;
970
+ updateParentDependencies(oldName: string, newName: string, singletonStorage: IHolderStorage, requestStorage?: IHolderStorage): void;
971
+ }
972
+ //#endregion
973
+ //#region src/internal/core/service-initializer.d.mts
974
+ /**
975
+ * Creates service instances from registry records.
976
+ *
977
+ * Handles both class-based (@Injectable) and factory-based (@Factory) services,
978
+ * managing the instantiation lifecycle including lifecycle hook invocation.
979
+ */
980
+ declare class ServiceInitializer {
981
+ private readonly injectors;
982
+ constructor(injectors: Injectors);
944
983
  /**
945
- * Finds services that are ready to be cleared in the current round.
946
- * A service is ready if all its dependencies have already been cleared.
984
+ * Instantiates a service based on its registry record.
985
+ * @param ctx The factory context for dependency injection
986
+ * @param record The factory record from the registry
987
+ * @param args Optional arguments for the service
988
+ * @returns Promise resolving to [undefined, instance] or [error]
947
989
  */
948
- private findServicesReadyForClearingInStorage;
990
+ instantiateService<T>(ctx: ServiceInitializationContext, record: FactoryRecord<T, any>, args?: any): Promise<[undefined, T] | [DIError]>;
949
991
  /**
950
- * Force clears services that couldn't be cleared through normal dependency resolution.
951
- * This handles edge cases like circular dependencies.
992
+ * Instantiates a class-based service (Injectable decorator).
993
+ * @param ctx The factory context for dependency injection
994
+ * @param record The factory record from the registry
995
+ * @param args Optional arguments for the service constructor
996
+ * @returns Promise resolving to [undefined, instance] or [error]
952
997
  */
953
- private forceClearServicesInStorage;
998
+ private instantiateClass;
954
999
  /**
955
- * Emits events to listeners for instance lifecycle events.
1000
+ * Instantiates a factory-based service (Factory decorator).
1001
+ * @param ctx The factory context for dependency injection
1002
+ * @param record The factory record from the registry
1003
+ * @param args Optional arguments for the factory
1004
+ * @returns Promise resolving to [undefined, instance] or [error]
956
1005
  */
957
- private emitInstanceEvent;
1006
+ private instantiateFactory;
958
1007
  }
959
1008
  //#endregion
960
- //#region src/internal/core/token-processor.d.mts
1009
+ //#region src/internal/core/instance-resolver.d.mts
961
1010
  /**
962
- * Handles token validation, normalization, and instance name generation.
1011
+ * Resolves instances from tokens, handling caching, creation, and scope rules.
963
1012
  *
964
- * Provides utilities for resolving tokens to their underlying InjectionToken,
965
- * validating arguments against schemas, and generating unique instance identifiers.
1013
+ * Uses unified storage for both singleton and request-scoped services.
1014
+ * Coordinates with ServiceInitializer for actual service creation.
1015
+ * Integrates ScopeTracker for automatic scope upgrades.
966
1016
  */
967
- declare class TokenProcessor {
1017
+ declare class InstanceResolver {
1018
+ private readonly registry;
1019
+ private readonly storage;
1020
+ private readonly serviceInitializer;
1021
+ private readonly tokenResolver;
1022
+ private readonly nameResolver;
1023
+ private readonly scopeTracker;
1024
+ private readonly serviceInvalidator;
1025
+ private readonly eventBus;
968
1026
  private readonly logger;
969
- private readonly instanceNameCache;
970
- constructor(logger?: Console | null);
1027
+ constructor(registry: Registry, storage: IHolderStorage, serviceInitializer: ServiceInitializer, tokenResolver: TokenResolver, nameResolver: NameResolver, scopeTracker: ScopeTracker, serviceInvalidator: ServiceInvalidator, eventBus: LifecycleEventBus, logger?: Console | null);
971
1028
  /**
972
- * Normalizes a token to an InjectionToken.
973
- * Handles class constructors by getting their injectable token.
1029
+ * Resolves an instance for the given token and arguments.
1030
+ * This method is used for singleton and transient services.
974
1031
  *
975
- * @param token A class constructor, InjectionToken, BoundInjectionToken, or FactoryInjectionToken
976
- * @returns The normalized InjectionTokenType
1032
+ * @param token The injection token
1033
+ * @param args Optional arguments
1034
+ * @param contextContainer The container to use for creating context
1035
+ * @param requestStorage Optional request storage (for scope upgrades)
1036
+ * @param requestId Optional request ID (for scope upgrades)
977
1037
  */
978
- normalizeToken(token: AnyInjectableType): InjectionTokenType;
1038
+ resolveInstance(token: AnyInjectableType, args: any, contextContainer: IContainer, requestStorage?: IHolderStorage, requestId?: string): Promise<[undefined, any] | [DIError]>;
979
1039
  /**
980
- * Gets the underlying "real" token from wrapped tokens.
981
- * For BoundInjectionToken and FactoryInjectionToken, returns the wrapped token.
982
- * For other tokens, returns the token itself.
1040
+ * Resolves a request-scoped instance for a ScopedContainer.
1041
+ * The service will be stored in the ScopedContainer's request storage.
983
1042
  *
984
- * @param token The token to unwrap
985
- * @returns The underlying InjectionToken
1043
+ * @param token The injection token
1044
+ * @param args Optional arguments
1045
+ * @param scopedContainer The ScopedContainer that owns the request context
986
1046
  */
987
- getRealToken<T = unknown>(token: InjectionTokenType): InjectionToken<T>;
1047
+ resolveRequestScopedInstance(token: AnyInjectableType, args: any, scopedContainer: ScopedContainer): Promise<[undefined, any] | [DIError]>;
988
1048
  /**
989
- * Convenience method that normalizes a token and then gets the real token.
990
- * Useful for checking registry entries where you need the actual registered token.
1049
+ * Unified resolution method that works with any IHolderStorage.
1050
+ * This eliminates duplication between singleton and request-scoped resolution.
991
1051
  *
992
- * @param token Any injectable type
993
- * @returns The underlying InjectionToken
1052
+ * IMPORTANT: The check-and-store logic is carefully designed to avoid race conditions.
1053
+ * The storage check and holder creation must happen synchronously (no awaits between).
1054
+ *
1055
+ * @param token The injection token
1056
+ * @param args Optional arguments
1057
+ * @param contextContainer The container for context
1058
+ * @param storage The storage strategy to use
1059
+ * @param scopedContainer Optional scoped container for request-scoped services
1060
+ * @param requestStorage Optional request storage (for scope upgrades)
1061
+ * @param requestId Optional request ID (for scope upgrades)
994
1062
  */
995
- getRegistryToken<T = unknown>(token: AnyInjectableType): InjectionToken<T>;
1063
+ private resolveWithStorage;
996
1064
  /**
997
- * Validates and resolves token arguments, handling factory token resolution and validation.
1065
+ * Internal method to resolve token args and create instance name.
1066
+ * Handles factory token resolution and validation.
998
1067
  */
999
- validateAndResolveTokenArgs(token: AnyInjectableType, args?: any): [DIError | undefined, {
1000
- actualToken: InjectionTokenType;
1001
- validatedArgs?: any;
1002
- }];
1068
+ private resolveTokenAndPrepareInstanceName;
1003
1069
  /**
1004
- * Generates a unique instance name based on token and arguments.
1005
- * Results are cached using an LRU cache for performance.
1070
+ * Handles storage error states (destroying, error, etc.).
1071
+ * Returns a result if handled, null if should proceed with creation.
1006
1072
  */
1007
- generateInstanceName(token: InjectionTokenType, args: any): string;
1073
+ private handleStorageError;
1008
1074
  /**
1009
- * Formats a single argument value for instance name generation.
1075
+ * Creates a new instance and stores it using the provided storage strategy.
1076
+ * This unified method replaces instantiateServiceFromRegistry and createRequestScopedInstance.
1077
+ *
1078
+ * For transient services, the instance is created but not stored (no caching).
1010
1079
  */
1011
- formatArgValue(value: any): string;
1080
+ private createAndStoreInstance;
1012
1081
  /**
1013
- * Creates a factory context for dependency injection during service instantiation.
1014
- * @param container The container instance (Container or ScopedContainer) for dependency resolution
1015
- * @param onDependencyResolved Callback when a dependency is resolved, receives the instance name
1082
+ * Creates a transient instance without storage or locking.
1083
+ * Each call creates a new instance.
1016
1084
  */
1017
- createFactoryContext(container: IContainer, onDependencyResolved?: (instanceName: string) => void): FactoryContext & {
1018
- getDestroyListeners: () => (() => void)[];
1019
- deps: Set<string>;
1020
- };
1021
- }
1022
- //#endregion
1023
- //#region src/internal/core/service-locator.d.mts
1024
- /**
1025
- * Core DI engine that coordinates service instantiation, resolution, and lifecycle.
1026
- *
1027
- * Acts as the central orchestrator for dependency injection operations,
1028
- * delegating to specialized components (InstanceResolver, Instantiator, Invalidator)
1029
- * for specific tasks.
1030
- */
1031
- declare class ServiceLocator {
1032
- private readonly registry;
1033
- private readonly logger;
1034
- private readonly injectors;
1035
- private readonly eventBus;
1036
- private readonly manager;
1037
- private readonly instantiator;
1038
- private readonly tokenProcessor;
1039
- private readonly invalidator;
1040
- private readonly instanceResolver;
1041
- constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
1042
- getEventBus(): LifecycleEventBus;
1043
- getManager(): HolderManager;
1044
- getInvalidator(): Invalidator;
1045
- getTokenProcessor(): TokenProcessor;
1046
- getInstanceIdentifier(token: AnyInjectableType, args?: any): string;
1085
+ private createTransientInstance;
1047
1086
  /**
1048
- * Gets or creates an instance for the given token.
1049
- * @param token The injection token
1050
- * @param args Optional arguments
1051
- * @param contextContainer The container to use for creating FactoryContext
1087
+ * Handles successful service instantiation.
1052
1088
  */
1053
- getInstance(token: AnyInjectableType, args: any, contextContainer: IContainer): Promise<any[]>;
1089
+ private handleInstantiationSuccess;
1054
1090
  /**
1055
- * Gets or throws an instance for the given token.
1056
- * @param token The injection token
1057
- * @param args Optional arguments
1058
- * @param contextContainer The container to use for creating FactoryContext
1091
+ * Handles service instantiation errors.
1059
1092
  */
1060
- getOrThrowInstance<Instance>(token: AnyInjectableType, args: any, contextContainer: IContainer): Promise<Instance>;
1093
+ private handleInstantiationError;
1061
1094
  /**
1062
- * Resolves a request-scoped service for a ScopedContainer.
1063
- * The service will be stored in the ScopedContainer's request context.
1064
- *
1065
- * @param token The injection token
1066
- * @param args Optional arguments
1067
- * @param scopedContainer The ScopedContainer that owns the request context
1095
+ * Handles instantiation result (success or error).
1068
1096
  */
1069
- resolveRequestScoped(token: AnyInjectableType, args: any, scopedContainer: ScopedContainer): Promise<any>;
1070
- getSyncInstance<Instance, Schema extends InjectionTokenSchemaType | undefined>(token: AnyInjectableType, args: Schema extends ZodObject ? z.input<Schema> : Schema extends ZodOptional<ZodObject> ? z.input<Schema> | undefined : undefined, contextContainer: IContainer): Instance | null;
1071
- invalidate(service: string, round?: number): Promise<any>;
1097
+ private handleInstantiationResult;
1072
1098
  /**
1073
- * Gracefully clears all services in the ServiceLocator using invalidation logic.
1074
- * This method respects service dependencies and ensures proper cleanup order.
1075
- * Services that depend on others will be invalidated first, then their dependencies.
1099
+ * Waits for an instance holder to be ready and returns the appropriate result.
1076
1100
  *
1077
- * @param options Optional configuration for the clearing process
1078
- * @returns Promise that resolves when all services have been cleared
1079
- */
1080
- clearAll(options?: ClearAllOptions): Promise<void>;
1081
- /**
1082
- * Waits for all services to settle (either created, destroyed, or error state).
1101
+ * @param holder The holder to wait for
1102
+ * @param waiterHolder Optional holder that is doing the waiting (for circular dependency detection)
1103
+ * @param getHolder Optional function to retrieve holders by name (required if waiterHolder is provided)
1083
1104
  */
1084
- ready(): Promise<void>;
1105
+ private waitForInstanceReady;
1085
1106
  /**
1086
- * Helper method for InstanceResolver to generate instance names.
1087
- * This is needed for the factory context creation.
1107
+ * Creates a ServiceInitializationContext for service instantiation.
1088
1108
  */
1089
- generateInstanceName(token: any, args: any): string;
1109
+ private createServiceInitializationContext;
1090
1110
  }
1091
1111
  //#endregion
1092
1112
  //#region src/container/container.d.mts
1093
1113
  /**
1094
1114
  * Main dependency injection container.
1095
1115
  *
1096
- * Provides a simplified public API for dependency injection, wrapping
1097
- * a ServiceLocator instance. Handles singleton and transient services directly,
1116
+ * Provides a simplified public API for dependency injection.
1117
+ * Handles singleton and transient services directly,
1098
1118
  * while request-scoped services require using beginRequest() to create a ScopedContainer.
1099
1119
  */
1100
- declare class Container implements IContainer {
1120
+ declare class Container extends AbstractContainer {
1101
1121
  protected readonly registry: Registry;
1102
1122
  protected readonly logger: Console | null;
1103
1123
  protected readonly injectors: Injectors;
1104
- private readonly serviceLocator;
1124
+ protected readonly defaultScope = InjectableScope.Singleton;
1125
+ protected readonly requestId: undefined;
1126
+ private readonly storage;
1127
+ private readonly serviceInitializer;
1128
+ private readonly serviceInvalidator;
1129
+ private readonly tokenResolver;
1130
+ private readonly nameResolver;
1131
+ private readonly scopeTracker;
1132
+ private readonly eventBus;
1133
+ private readonly instanceResolver;
1105
1134
  private readonly activeRequestIds;
1106
1135
  constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
1107
1136
  private registerSelf;
1108
1137
  /**
1109
1138
  * Gets an instance from the container.
1110
- * This method has the same type signature as the inject method from get-injectors.mts
1111
- *
1112
1139
  * NOTE: Request-scoped services cannot be resolved directly from Container.
1113
1140
  * Use beginRequest() to create a ScopedContainer for request-scoped services.
1114
1141
  */
@@ -1120,87 +1147,46 @@ declare class Container implements IContainer {
1120
1147
  get<T>(token: BoundInjectionToken<T, any>): Promise<T>;
1121
1148
  get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
1122
1149
  /**
1123
- * Gets an instance with a specific container context.
1124
- * Used by ScopedContainer to delegate singleton/transient resolution
1125
- * while maintaining the correct container context for nested inject() calls.
1126
- *
1127
- * @internal
1128
- */
1129
- getWithContext(token: ClassType | InjectionToken<any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>, args: unknown, contextContainer: IContainer): Promise<any>;
1130
- /**
1131
- * Resolves a request-scoped service for a ScopedContainer.
1132
- * The service will be stored in the ScopedContainer's request context.
1133
- *
1134
- * @internal
1135
- */
1136
- resolveForRequest(token: ClassType | InjectionToken<any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>, args: unknown, scopedContainer: ScopedContainer): Promise<any>;
1137
- /**
1138
- * Gets the underlying ServiceLocator instance for advanced usage
1139
- */
1140
- getServiceLocator(): ServiceLocator;
1141
- /**
1142
- * Gets the registry
1143
- */
1144
- getRegistry(): Registry;
1145
- /**
1146
- * Invalidates a service and its dependencies
1150
+ * Invalidates a service and its dependencies.
1147
1151
  */
1148
1152
  invalidate(service: unknown): Promise<void>;
1149
1153
  /**
1150
- * Gets a service holder by instance (reverse lookup)
1151
- */
1152
- private getHolderByInstance;
1153
- /**
1154
- * Checks if a service is registered in the container
1155
- */
1156
- isRegistered(token: any): boolean;
1157
- /**
1158
- * Disposes the container and cleans up all resources
1154
+ * Disposes the container and cleans up all resources.
1159
1155
  */
1160
1156
  dispose(): Promise<void>;
1161
- /**
1162
- * Waits for all pending operations to complete
1163
- */
1164
- ready(): Promise<void>;
1165
1157
  /**
1166
1158
  * @internal
1167
1159
  * Attempts to get an instance synchronously if it already exists.
1168
- * Returns null if the instance doesn't exist or is not ready.
1160
+ * Overrides base class to support requestId parameter for ScopedContainer compatibility.
1169
1161
  */
1170
- tryGetSync<T>(token: any, args?: any): T | null;
1162
+ tryGetSync<T>(token: any, args?: any, requestId?: string): T | null;
1171
1163
  /**
1172
1164
  * Begins a new request context and returns a ScopedContainer.
1173
- *
1174
- * The ScopedContainer provides isolated request-scoped service resolution
1175
- * while delegating singleton and transient services to this Container.
1176
- *
1177
- * @param requestId Unique identifier for this request
1178
- * @param metadata Optional metadata for the request
1179
- * @param priority Priority for resolution (higher = more priority)
1180
- * @returns A ScopedContainer for this request
1181
1165
  */
1182
- beginRequest(requestId: string, metadata?: Record<string, any>, priority?: number): ScopedContainer;
1166
+ beginRequest(requestId: string, metadata?: Record<string, any>): ScopedContainer;
1183
1167
  /**
1184
- * Removes a request ID from the active set.
1185
- * Called by ScopedContainer when the request ends.
1186
- *
1187
- * @internal
1188
- */
1189
- removeActiveRequest(requestId: string): void;
1190
- /**
1191
- * Gets the set of active request IDs.
1168
+ * Gets all active request IDs.
1192
1169
  */
1193
1170
  getActiveRequestIds(): ReadonlySet<string>;
1194
1171
  /**
1195
- * Checks if a request ID is currently active.
1172
+ * Checks if a request is active.
1196
1173
  */
1197
1174
  hasActiveRequest(requestId: string): boolean;
1198
1175
  /**
1199
- * Clears all instances and bindings from the container.
1200
- * This is useful for testing or resetting the container state.
1176
+ * Removes a request ID from active requests.
1177
+ * Called by ScopedContainer when request ends.
1201
1178
  */
1202
- clear(): Promise<void>;
1179
+ removeRequestId(requestId: string): void;
1180
+ getStorage(): UnifiedStorage;
1181
+ getServiceInitializer(): ServiceInitializer;
1182
+ getServiceInvalidator(): ServiceInvalidator;
1183
+ getTokenResolver(): TokenResolver;
1184
+ getNameResolver(): NameResolver;
1185
+ getScopeTracker(): ScopeTracker;
1186
+ getEventBus(): LifecycleEventBus;
1187
+ getRegistry(): Registry;
1188
+ getInstanceResolver(): InstanceResolver;
1203
1189
  }
1204
1190
  //#endregion
1205
- export { InjectState as $, InjectableScope as A, ClassTypeWithoutArguments as B, InstanceStatus as C, Registry as D, FactoryRecord as E, ClassTypeWithArgument as F, OptionalInjectionTokenSchemaType as G, InjectionToken as H, ClassTypeWithInstance as I, getInjectors as J, FactoryContext as K, ClassTypeWithInstanceAndArgument as L, BaseInjectionTokenSchemaType as M, BoundInjectionToken as N, globalRegistry as O, ClassType as P, InjectRequest as Q, ClassTypeWithInstanceAndOptionalArgument as R, InstanceHolderError as S, DIErrorCode as T, InjectionTokenSchemaType as U, FactoryInjectionToken as V, InjectionTokenType as W, Factorable as X, IContainer as Y, FactorableWithArgs as Z, InstanceEffect as _, HolderManager as a, UnionToOvlds as at, InstanceHolderCreating as b, DefaultRequestContext as c, createRequestContext as d, IsUnion as et, BaseHolderManager as f, InstanceDestroyListener as g, IHolderStorage as h, Invalidator as i, UnionToIntersection as it, AnyInjectableType as j, InjectableType as k, RequestContext as l, HolderGetResult as m, ServiceLocator as n, PopUnion as nt, LifecycleEventBus as o, HolderReadyResult as p, Injectors as q, TokenProcessor as r, UnionToArray as rt, ScopedContainer as s, Container as t, Join as tt, RequestContextHolder as u, InstanceHolder as v, DIError as w, InstanceHolderDestroying as x, InstanceHolderCreated as y, ClassTypeWithOptionalArgument as z };
1206
- //# sourceMappingURL=container-YPwvmlK2.d.cts.map
1191
+ export { ClassTypeWithoutArguments as $, Injectors as A, PopUnion as B, NameResolver as C, Factorable as D, globalRegistry as E, IContainer as F, BaseInjectionTokenSchemaType as G, UnionToIntersection as H, InjectRequest as I, ClassTypeWithArgument as J, BoundInjectionToken as K, InjectState as L, ServiceInitializationContext as M, InjectableType as N, FactorableWithArgs as O, InjectableScope as P, ClassTypeWithOptionalArgument as Q, IsUnion as R, DIErrorCode as S, Registry as T, UnionToOvlds as U, UnionToArray as V, AnyInjectableType as W, ClassTypeWithInstanceAndArgument as X, ClassTypeWithInstance as Y, ClassTypeWithInstanceAndOptionalArgument as Z, InstanceHolderCreating as _, ScopedContainer as a, InstanceStatus as b, ClearAllOptions as c, LifecycleEventBus as d, FactoryInjectionToken as et, HolderGetResult as f, InstanceHolderCreated as g, InstanceHolder as h, ScopeTracker as i, OptionalInjectionTokenSchemaType as it, getInjectors as j, FactoryContext as k, InvalidationOptions as l, InstanceDestroyListener as m, InstanceResolver as n, InjectionTokenSchemaType as nt, UnifiedStorage as o, IHolderStorage as p, ClassType as q, ServiceInitializer as r, InjectionTokenType as rt, TokenResolver as s, Container as t, InjectionToken as tt, ServiceInvalidator as u, InstanceHolderDestroying as v, FactoryRecord as w, DIError as x, InstanceHolderError as y, Join as z };
1192
+ //# sourceMappingURL=container-D-0Ho3qL.d.cts.map