@asenajs/ioc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +2 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/lib/CircularDependencyDetector.d.ts +49 -0
  7. package/dist/lib/CircularDependencyDetector.js +69 -0
  8. package/dist/lib/CircularDependencyDetector.js.map +1 -0
  9. package/dist/lib/Container.d.ts +247 -0
  10. package/dist/lib/Container.js +563 -0
  11. package/dist/lib/Container.js.map +1 -0
  12. package/dist/lib/IocApplication.d.ts +88 -0
  13. package/dist/lib/IocApplication.js +110 -0
  14. package/dist/lib/IocApplication.js.map +1 -0
  15. package/dist/lib/IocEngine.d.ts +173 -0
  16. package/dist/lib/IocEngine.js +725 -0
  17. package/dist/lib/IocEngine.js.map +1 -0
  18. package/dist/lib/component/Scope.d.ts +4 -0
  19. package/dist/lib/component/Scope.js +6 -0
  20. package/dist/lib/component/Scope.js.map +1 -0
  21. package/dist/lib/component/componentRegistry.d.ts +34 -0
  22. package/dist/lib/component/componentRegistry.js +134 -0
  23. package/dist/lib/component/componentRegistry.js.map +1 -0
  24. package/dist/lib/component/componentUtils.d.ts +16 -0
  25. package/dist/lib/component/componentUtils.js +44 -0
  26. package/dist/lib/component/componentUtils.js.map +1 -0
  27. package/dist/lib/component/decorators/Component.d.ts +8 -0
  28. package/dist/lib/component/decorators/Component.js +12 -0
  29. package/dist/lib/component/decorators/Component.js.map +1 -0
  30. package/dist/lib/component/decorators/Implements.d.ts +7 -0
  31. package/dist/lib/component/decorators/Implements.js +14 -0
  32. package/dist/lib/component/decorators/Implements.js.map +1 -0
  33. package/dist/lib/component/decorators/Inject.d.ts +29 -0
  34. package/dist/lib/component/decorators/Inject.js +82 -0
  35. package/dist/lib/component/decorators/Inject.js.map +1 -0
  36. package/dist/lib/component/decorators/OnStart.d.ts +20 -0
  37. package/dist/lib/component/decorators/OnStart.js +33 -0
  38. package/dist/lib/component/decorators/OnStart.js.map +1 -0
  39. package/dist/lib/component/decorators/OnStop.d.ts +15 -0
  40. package/dist/lib/component/decorators/OnStop.js +28 -0
  41. package/dist/lib/component/decorators/OnStop.js.map +1 -0
  42. package/dist/lib/component/decorators/PostConstruct.d.ts +14 -0
  43. package/dist/lib/component/decorators/PostConstruct.js +16 -0
  44. package/dist/lib/component/decorators/PostConstruct.js.map +1 -0
  45. package/dist/lib/component/decorators/PostProcessor.d.ts +25 -0
  46. package/dist/lib/component/decorators/PostProcessor.js +29 -0
  47. package/dist/lib/component/decorators/PostProcessor.js.map +1 -0
  48. package/dist/lib/component/decorators/Service.d.ts +8 -0
  49. package/dist/lib/component/decorators/Service.js +12 -0
  50. package/dist/lib/component/decorators/Service.js.map +1 -0
  51. package/dist/lib/component/decorators/Strategy.d.ts +9 -0
  52. package/dist/lib/component/decorators/Strategy.js +29 -0
  53. package/dist/lib/component/decorators/Strategy.js.map +1 -0
  54. package/dist/lib/component/decorators/Value.d.ts +29 -0
  55. package/dist/lib/component/decorators/Value.js +41 -0
  56. package/dist/lib/component/decorators/Value.js.map +1 -0
  57. package/dist/lib/component/decorators/index.d.ts +11 -0
  58. package/dist/lib/component/decorators/index.js +12 -0
  59. package/dist/lib/component/decorators/index.js.map +1 -0
  60. package/dist/lib/component/decorators/legacyDecorator.d.ts +15 -0
  61. package/dist/lib/component/decorators/legacyDecorator.js +24 -0
  62. package/dist/lib/component/decorators/legacyDecorator.js.map +1 -0
  63. package/dist/lib/component/index.d.ts +3 -0
  64. package/dist/lib/component/index.js +4 -0
  65. package/dist/lib/component/index.js.map +1 -0
  66. package/dist/lib/constants/ComponentConstants.d.ts +21 -0
  67. package/dist/lib/constants/ComponentConstants.js +25 -0
  68. package/dist/lib/constants/ComponentConstants.js.map +1 -0
  69. package/dist/lib/constants/index.d.ts +1 -0
  70. package/dist/lib/constants/index.js +2 -0
  71. package/dist/lib/constants/index.js.map +1 -0
  72. package/dist/lib/decorators/CoreService.d.ts +11 -0
  73. package/dist/lib/decorators/CoreService.js +30 -0
  74. package/dist/lib/decorators/CoreService.js.map +1 -0
  75. package/dist/lib/decorators/index.d.ts +1 -0
  76. package/dist/lib/decorators/index.js +2 -0
  77. package/dist/lib/decorators/index.js.map +1 -0
  78. package/dist/lib/helper/fileHelper.d.ts +1 -0
  79. package/dist/lib/helper/fileHelper.js +29 -0
  80. package/dist/lib/helper/fileHelper.js.map +1 -0
  81. package/dist/lib/helper/iocHelper.d.ts +2 -0
  82. package/dist/lib/helper/iocHelper.js +12 -0
  83. package/dist/lib/helper/iocHelper.js.map +1 -0
  84. package/dist/lib/helper/valueResolver.d.ts +24 -0
  85. package/dist/lib/helper/valueResolver.js +37 -0
  86. package/dist/lib/helper/valueResolver.js.map +1 -0
  87. package/dist/lib/index.d.ts +12 -0
  88. package/dist/lib/index.js +13 -0
  89. package/dist/lib/index.js.map +1 -0
  90. package/dist/lib/lifecycle/LifecycleService.d.ts +78 -0
  91. package/dist/lib/lifecycle/LifecycleService.js +181 -0
  92. package/dist/lib/lifecycle/LifecycleService.js.map +1 -0
  93. package/dist/lib/lifecycle/LifecycleState.d.ts +20 -0
  94. package/dist/lib/lifecycle/LifecycleState.js +22 -0
  95. package/dist/lib/lifecycle/LifecycleState.js.map +1 -0
  96. package/dist/lib/lifecycle/index.d.ts +2 -0
  97. package/dist/lib/lifecycle/index.js +3 -0
  98. package/dist/lib/lifecycle/index.js.map +1 -0
  99. package/dist/lib/logger/IocLogger.d.ts +35 -0
  100. package/dist/lib/logger/IocLogger.js +2 -0
  101. package/dist/lib/logger/IocLogger.js.map +1 -0
  102. package/dist/lib/logger/index.d.ts +1 -0
  103. package/dist/lib/logger/index.js +2 -0
  104. package/dist/lib/logger/index.js.map +1 -0
  105. package/dist/lib/types/Class.d.ts +1 -0
  106. package/dist/lib/types/Class.js +2 -0
  107. package/dist/lib/types/Class.js.map +1 -0
  108. package/dist/lib/types/ComponentPostProcessor.d.ts +30 -0
  109. package/dist/lib/types/ComponentPostProcessor.js +2 -0
  110. package/dist/lib/types/ComponentPostProcessor.js.map +1 -0
  111. package/dist/lib/types/ContainerService.d.ts +6 -0
  112. package/dist/lib/types/ContainerService.js +2 -0
  113. package/dist/lib/types/ContainerService.js.map +1 -0
  114. package/dist/lib/types/ICoreService.d.ts +9 -0
  115. package/dist/lib/types/ICoreService.js +2 -0
  116. package/dist/lib/types/ICoreService.js.map +1 -0
  117. package/dist/lib/types/ICoreServiceNames.d.ts +10 -0
  118. package/dist/lib/types/ICoreServiceNames.js +12 -0
  119. package/dist/lib/types/ICoreServiceNames.js.map +1 -0
  120. package/dist/lib/types/InjectableComponent.d.ts +42 -0
  121. package/dist/lib/types/InjectableComponent.js +2 -0
  122. package/dist/lib/types/InjectableComponent.js.map +1 -0
  123. package/dist/lib/types/IocConfig.d.ts +11 -0
  124. package/dist/lib/types/IocConfig.js +2 -0
  125. package/dist/lib/types/IocConfig.js.map +1 -0
  126. package/dist/lib/types/LifecycleComponent.d.ts +29 -0
  127. package/dist/lib/types/LifecycleComponent.js +2 -0
  128. package/dist/lib/types/LifecycleComponent.js.map +1 -0
  129. package/dist/lib/types/decorators/ComponentParams.d.ts +5 -0
  130. package/dist/lib/types/decorators/ComponentParams.js +2 -0
  131. package/dist/lib/types/decorators/ComponentParams.js.map +1 -0
  132. package/dist/lib/types/decorators/ComponentType.d.ts +14 -0
  133. package/dist/lib/types/decorators/ComponentType.js +10 -0
  134. package/dist/lib/types/decorators/ComponentType.js.map +1 -0
  135. package/dist/lib/types/decorators/ServiceParams.d.ts +2 -0
  136. package/dist/lib/types/decorators/ServiceParams.js +2 -0
  137. package/dist/lib/types/decorators/ServiceParams.js.map +1 -0
  138. package/dist/lib/types/index.d.ts +11 -0
  139. package/dist/lib/types/index.js +12 -0
  140. package/dist/lib/types/index.js.map +1 -0
  141. package/dist/lib/utils/errorChain.d.ts +4 -0
  142. package/dist/lib/utils/errorChain.js +29 -0
  143. package/dist/lib/utils/errorChain.js.map +1 -0
  144. package/dist/lib/utils/typedMetadata.d.ts +54 -0
  145. package/dist/lib/utils/typedMetadata.js +97 -0
  146. package/dist/lib/utils/typedMetadata.js.map +1 -0
  147. package/package.json +73 -4
@@ -0,0 +1,563 @@
1
+ import { ComponentConstants } from './constants';
2
+ import { getOwnTypedMetadata, getTypedMetadata } from './utils/typedMetadata';
3
+ import { CircularDependencyDetector } from './CircularDependencyDetector';
4
+ import { CORE_SERVICE } from './decorators';
5
+ import { collectValueFields, readValue } from './helper/valueResolver';
6
+ /**
7
+ * Thrown by {@link Container.resolve} when the requested key has no registration.
8
+ *
9
+ * Carries no information about who needed the key - `resolve` cannot know that - so
10
+ * `injectDependencies` catches it and rethrows with the dependent class and field attached.
11
+ * The subclass identity is what tells an unwrapped miss (wrap it) from any other failure
12
+ * (rethrow untouched), including an already-wrapped nested miss.
13
+ */
14
+ export class UnregisteredDependencyError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = 'UnregisteredDependencyError';
18
+ }
19
+ }
20
+ export class Container {
21
+ _services = {};
22
+ circularDetector = new CircularDependencyDetector();
23
+ postProcessors = [];
24
+ overriddenKeys = new Set();
25
+ /** Key -> entries that live there only as an alias of their own key (see `registerAlias`). */
26
+ aliases = new Map();
27
+ /**
28
+ * How the error for an assignment to a wired field ends: what to do instead. Whatever wraps
29
+ * the container names its own way of seeding a test double here.
30
+ */
31
+ injectedFieldHint = "To swap a dependency in a test, seed a double with overrideInstance(), or the 'overrides' option of " +
32
+ 'IocApplication.create(), before the components are registered.';
33
+ /**
34
+ * Whether construction runs start hooks itself.
35
+ *
36
+ * `immediate` is the original behaviour and stays that way for core services, for the
37
+ * post-processor closure the IoC engine registers ahead of everything else, and for every
38
+ * transient. `deferred` holds the hooks back so `LifecycleService` can run them from
39
+ * `start()`, once the whole graph exists.
40
+ */
41
+ startHookMode = 'immediate';
42
+ /**
43
+ * Every singleton built by `register()`, in registration order - which the IoC engine has
44
+ * already topologically sorted, so dependencies come before dependents. Start hooks walk it
45
+ * forwards, stop hooks backwards.
46
+ *
47
+ * Instances handed in through `registerInstance()` are deliberately absent: nothing ever ran
48
+ * a start hook on them, so there is no started/stopped pair to keep symmetric.
49
+ */
50
+ lifecycleComponents = [];
51
+ constructor(services) {
52
+ this._services = services || {};
53
+ }
54
+ /**
55
+ * @returns {Promise<ContainerService>} The new entry, or the test double's entry when `key` is overridden
56
+ */
57
+ async register(key, Class, singleton) {
58
+ // An overridden key keeps its test double. Returning early means the real class is
59
+ // never instantiated (no @PostConstruct side effects) and the entry never turns
60
+ // into an array, which is what resolve() would otherwise hand back.
61
+ if (this.overriddenKeys.has(key)) {
62
+ return this._services[key];
63
+ }
64
+ const instance = singleton ? await this.prepareInstance(Class) : null;
65
+ if (singleton) {
66
+ this.trackLifecycle(key, instance, Class);
67
+ }
68
+ const entry = { Class, instance, singleton };
69
+ this.store(key, entry);
70
+ return entry;
71
+ }
72
+ /**
73
+ * @description Make an entry registered under one key reachable under another as well.
74
+ *
75
+ * The entry object itself is shared, so a singleton keeps one instance and one lifecycle no
76
+ * matter how many keys reach it - `@Implements` registers a component under its name and its
77
+ * interface key this way. Component scans (`resolveAll`) skip alias positions, so the
78
+ * component is still found exactly once.
79
+ *
80
+ * @param {string} key - The additional key, e.g. an `@Implements` interface name
81
+ * @param {ContainerService} entry - An entry returned by `register()`
82
+ * @returns {void}
83
+ */
84
+ registerAlias(key, entry) {
85
+ if (this.overriddenKeys.has(key)) {
86
+ return;
87
+ }
88
+ this.store(key, entry);
89
+ let aliased = this.aliases.get(key);
90
+ if (!aliased) {
91
+ aliased = new Set();
92
+ this.aliases.set(key, aliased);
93
+ }
94
+ aliased.add(entry);
95
+ }
96
+ store(key, entry) {
97
+ const existing = this._services[key];
98
+ if (!existing) {
99
+ this._services[key] = entry;
100
+ }
101
+ else if (Array.isArray(existing)) {
102
+ existing.push(entry);
103
+ }
104
+ else {
105
+ this._services[key] = [existing, entry];
106
+ }
107
+ }
108
+ /**
109
+ * @description Record a singleton for the start/stop lifecycle.
110
+ *
111
+ * `started` reflects what already happened rather than what is planned: a component built in
112
+ * immediate mode has run its start hooks by the time it gets here, so it is stoppable at once.
113
+ * A deferred one is not started until `LifecycleService` says so - and a component that never
114
+ * started must never be stopped.
115
+ *
116
+ * @param {string} key - Service identifier
117
+ * @param {unknown} instance - The post-processed instance
118
+ * @param {Class} Class - The class it was built from
119
+ * @returns {void}
120
+ */
121
+ trackLifecycle(key, instance, Class) {
122
+ this.lifecycleComponents.push({
123
+ key,
124
+ instance,
125
+ Class,
126
+ started: this.startHookMode === 'immediate',
127
+ });
128
+ }
129
+ /**
130
+ * @description Register an already-created instance directly
131
+ * Useful for dependencies created outside the container, like the logger. Any value except
132
+ * `null` and `undefined` can be registered, including `0`, `''`, `false` and an empty array.
133
+ * @param {string} key - Service identifier
134
+ * @param {T} instance - Pre-created instance
135
+ * @returns {Promise<void>}
136
+ */
137
+ async registerInstance(key, instance) {
138
+ if (this._services[key]) {
139
+ throw new Error(`Service '${key}' is already registered`);
140
+ }
141
+ if (instance === null || instance === undefined) {
142
+ throw new Error(`Cannot register '${key}' as ${instance === null ? 'null' : 'undefined'} - ` +
143
+ 'an instance has to be a value. Leave the name out instead of registering nothing under it.');
144
+ }
145
+ this._services[key] = {
146
+ Class: (instance.constructor ?? Object),
147
+ instance: instance,
148
+ singleton: true,
149
+ };
150
+ }
151
+ /**
152
+ * @description Replace a service with a pre-created test double (Spring's @MockBean).
153
+ *
154
+ * Seeds the container before user components are registered: any later `register()`
155
+ * call for the same key becomes a no-op, so the real class is never constructed and
156
+ * dependents capture the override in their injection closures.
157
+ *
158
+ * @param {string} key - Service identifier to override
159
+ * @param {T} instance - Replacement instance
160
+ * @returns {void}
161
+ */
162
+ overrideInstance(key, instance) {
163
+ if (instance === null || instance === undefined) {
164
+ throw new Error(`Cannot override service '${key}' with ${instance === null ? 'null' : 'undefined'} - ` +
165
+ 'an override must be an object instance. ' +
166
+ 'A null override would fail later with an opaque "instance cannot be null" error at resolve time.');
167
+ }
168
+ this.overriddenKeys.add(key);
169
+ this._services[key] = {
170
+ Class: (instance.constructor ?? Object),
171
+ instance,
172
+ singleton: true,
173
+ };
174
+ }
175
+ /**
176
+ * @description Check whether a key has been replaced by an override
177
+ * @param {string} key - Service key
178
+ * @returns {boolean}
179
+ */
180
+ isOverridden(key) {
181
+ return this.overriddenKeys.has(key);
182
+ }
183
+ async resolve(key) {
184
+ // Check circular dependency
185
+ this.circularDetector.checkCircular(key);
186
+ this.circularDetector.push(key);
187
+ try {
188
+ const service = this._services[key];
189
+ if (!service) {
190
+ throw new UnregisteredDependencyError(key + ' is not registered');
191
+ }
192
+ if (Array.isArray(service)) {
193
+ return await this.resolveMultipleContainerService(service);
194
+ }
195
+ return await this.resolveContainerService(service);
196
+ }
197
+ finally {
198
+ this.circularDetector.pop(key);
199
+ }
200
+ }
201
+ /**
202
+ * @description Check if a service is registered without resolving it
203
+ * @param {string} key - Service key
204
+ * @returns {boolean}
205
+ */
206
+ has(key) {
207
+ return this._services[key] !== undefined;
208
+ }
209
+ /**
210
+ * @description Resolve every implementation registered under a strategy key.
211
+ *
212
+ * Cardinality is normalized here rather than borrowed from resolve(). `_services[key]` has
213
+ * three shapes - absent, a bare ContainerService, an array - and resolve() maps them to
214
+ * throw / T / T[]. That is right for @Inject, whose dependency is single-valued: it is
215
+ * either there or the component is broken. @Strategy is multi-valued by construction, so
216
+ * zero is a cardinality it has to be able to take (a plugin point before its first plugin)
217
+ * and one has to arrive as a one-element array like any other count.
218
+ *
219
+ * This used to be a cast over resolve(), which made it correct at exactly one cardinality:
220
+ * an empty key aborted the boot, and a single implementation was injected as a bare
221
+ * instance whose first `.length` / `for...of` / `.map()` failed at runtime.
222
+ *
223
+ * @param {string} key - Strategy (interface) key
224
+ * @returns {Promise<T[]>} Every implementation, empty when the key has none
225
+ */
226
+ async resolveStrategy(key) {
227
+ // Kept from resolve(): a cycle running through a strategy key must still be reported
228
+ // rather than recursing until the stack overflows
229
+ this.circularDetector.checkCircular(key);
230
+ this.circularDetector.push(key);
231
+ try {
232
+ const service = this._services[key];
233
+ if (!service) {
234
+ return [];
235
+ }
236
+ return Array.isArray(service)
237
+ ? await this.resolveMultipleContainerService(service)
238
+ : [await this.resolveContainerService(service)];
239
+ }
240
+ finally {
241
+ this.circularDetector.pop(key);
242
+ }
243
+ }
244
+ /**
245
+ * @typeOfComponent is the type of the component
246
+ *
247
+ * */
248
+ async resolveAll(typeOfComponent) {
249
+ const matchingServices = this.filterServices(typeOfComponent);
250
+ if (!matchingServices.length) {
251
+ return null;
252
+ }
253
+ const instances = [];
254
+ for (const containerService of matchingServices) {
255
+ if (Array.isArray(containerService)) {
256
+ instances.push(await this.resolveMultipleContainerService(containerService));
257
+ }
258
+ else {
259
+ instances.push(await this.resolveContainerService(containerService));
260
+ }
261
+ }
262
+ return instances;
263
+ }
264
+ filterServices(typeOfComponent) {
265
+ const matches = [];
266
+ for (const [key, value] of Object.entries(this._services)) {
267
+ const aliased = this.aliases.get(key);
268
+ const entries = (Array.isArray(value) ? value : [value]).filter((entry) => !aliased?.has(entry));
269
+ // Own-only, like component identity itself. Walking the chain here meant a @Service
270
+ // extending a component of another kind answered true for that kind, so it was
271
+ // resolved as one - without any of the own-only metadata that kind relies on.
272
+ if (!entries.length || !entries.every((entry) => getOwnTypedMetadata(typeOfComponent, entry.Class))) {
273
+ continue;
274
+ }
275
+ matches.push(entries.length > 1 ? entries : entries[0]);
276
+ }
277
+ return matches;
278
+ }
279
+ async resolveContainerService(containerService) {
280
+ if (!containerService.singleton) {
281
+ return await this.prepareInstance(containerService.Class);
282
+ }
283
+ if (containerService.instance === null || containerService.instance === undefined) {
284
+ throw new Error('instance cannot be null');
285
+ }
286
+ return containerService.instance;
287
+ }
288
+ async resolveMultipleContainerService(containerService) {
289
+ return Promise.all(containerService.map(async (_service) => this.resolveContainerService(_service)));
290
+ }
291
+ /**
292
+ * @description Register a ComponentPostProcessor for post-processing newly created instances.
293
+ * PostProcessors are called in FIFO order after DI + PostConstruct.
294
+ * @param {ComponentPostProcessor} processor - The post-processor to register
295
+ */
296
+ registerPostProcessor(processor) {
297
+ this.postProcessors.push(processor);
298
+ }
299
+ /**
300
+ * @description Choose whether construction runs start hooks or hands them to LifecycleService.
301
+ *
302
+ * The IoC engine switches to `deferred` around user components only. Post-processors keep
303
+ * running theirs at construction because `postProcess()` reads state a start hook sets - defer
304
+ * that and every component the processor wraps is built against an uninitialised processor.
305
+ *
306
+ * @param {StartHookMode} mode - immediate (default) or deferred
307
+ * @returns {void}
308
+ */
309
+ setStartHookMode(mode) {
310
+ this.startHookMode = mode;
311
+ }
312
+ /**
313
+ * @description Singletons in registration order, for the start/stop lifecycle.
314
+ * @returns {LifecycleComponent[]} The live list - LifecycleService flips `started` on it
315
+ */
316
+ get lifecycle() {
317
+ return this.lifecycleComponents;
318
+ }
319
+ async prepareInstance(Class) {
320
+ const newInstance = new Class();
321
+ this.injectValues(newInstance, Class); // configuration injection
322
+ await this.injectDependencies(newInstance, Class); // dependency injection
323
+ await this.injectStrategies(newInstance, Class); // strategy injection
324
+ // Post-processing (skipped when postProcessors is empty - zero overhead)
325
+ let processed = newInstance;
326
+ for (const processor of this.postProcessors) {
327
+ processed = (await processor.postProcess(processed, Class)) ?? processed;
328
+ }
329
+ // Deferred mode leaves the start hooks to LifecycleService. The hook runs against the
330
+ // *processed* instance either way - a post-processor may have returned a proxy, and the
331
+ // hook has to see the same object every other component was injected with.
332
+ if (this.startHookMode === 'immediate') {
333
+ await this.executeStartHooks(processed, Class);
334
+ }
335
+ return processed;
336
+ }
337
+ /**
338
+ * @description Run every @OnStart (and its @PostConstruct alias) method on an instance.
339
+ *
340
+ * Walks the prototype chain ancestors-first and runs each method name once, so a hook
341
+ * inherited by three classes still fires once.
342
+ *
343
+ * A failure used to `process.exit(1)` here, which turned one broken component into a suite
344
+ * reporting `0 pass / 1 fail` with no indication of why. It now throws, naming the hook, with
345
+ * the original error as `cause` - the boot fails, the process decides what to do about it.
346
+ *
347
+ * @param {any} instance - The instance to run hooks on
348
+ * @param {Class} Class - The class of the instance
349
+ * @returns {Promise<void>}
350
+ */
351
+ async executeStartHooks(instance, Class) {
352
+ for (const hook of this.collectHookMethods(Class, ComponentConstants.PostConstructKey)) {
353
+ try {
354
+ await instance[hook]();
355
+ }
356
+ catch (error) {
357
+ throw new Error(`@OnStart hook '${Class.name}.${hook}()' failed`, { cause: error });
358
+ }
359
+ }
360
+ }
361
+ /**
362
+ * @description The @OnStop method names for a class, in the order they should run.
363
+ *
364
+ * Reversed relative to the start hooks so a component tears down in the opposite order it
365
+ * was brought up, matching how LifecycleService walks the components themselves.
366
+ *
367
+ * @param {Class} Class - The class to inspect
368
+ * @returns {string[]} Method names, empty when the class declares none
369
+ */
370
+ getStopHooks(Class) {
371
+ return this.collectHookMethods(Class, ComponentConstants.OnStopKey).reverse();
372
+ }
373
+ /**
374
+ * @description The @OnStart method names for a class, in the order they run.
375
+ * @param {Class} Class - The class to inspect
376
+ * @returns {string[]} Method names, empty when the class declares none
377
+ */
378
+ getStartHooks(Class) {
379
+ return this.collectHookMethods(Class, ComponentConstants.PostConstructKey);
380
+ }
381
+ /**
382
+ * @description Collect decorated method names across the prototype chain, de-duplicated.
383
+ * @param {Class} Class - The class to inspect
384
+ * @param {symbol} metadataKey - Which hook list to read
385
+ * @returns {string[]} Method names, ancestors first
386
+ */
387
+ collectHookMethods(Class, metadataKey) {
388
+ const prototypeChain = this.getPrototypeChain(Class);
389
+ const methods = [];
390
+ const seen = new Set();
391
+ for (const classInChain of prototypeChain.reverse()) {
392
+ const hooks = getOwnTypedMetadata(metadataKey, classInChain);
393
+ if (!hooks) {
394
+ continue;
395
+ }
396
+ for (const hook of hooks) {
397
+ // Skip if already collected (prevents duplicate execution in inheritance chain)
398
+ if (seen.has(hook)) {
399
+ continue;
400
+ }
401
+ seen.add(hook);
402
+ methods.push(hook);
403
+ }
404
+ }
405
+ return methods;
406
+ }
407
+ async injectStrategies(newInstance, Class) {
408
+ const prototypeChain = this.getPrototypeChain(Class);
409
+ for (const classInChain of prototypeChain.reverse()) {
410
+ const strategyList = getOwnTypedMetadata(ComponentConstants.StrategyKey, classInChain);
411
+ if (!strategyList)
412
+ continue;
413
+ for (const [propertyKey, interfaceName] of Object.entries(strategyList)) {
414
+ if (!interfaceName) {
415
+ continue;
416
+ }
417
+ if (typeof interfaceName !== 'string') {
418
+ throw new Error('interfaceName must be a string');
419
+ }
420
+ // Same guard shape as injectDependencies, deliberately. Testing for the *descriptor*
421
+ // broke two ways: the chain runs ancestors-first, so a base class's accessor made the
422
+ // subclass's @Strategy override look "already set" and it was skipped; and under
423
+ // `useDefineForClassFields` (the default at ES2022+) an initializer-less field is an
424
+ // own property `= undefined` at construction, so the strategy was never injected at
425
+ // all. Bun's transpiler uses Set semantics, which is why running from source hides it.
426
+ const strategyProperty = Object.getOwnPropertyDescriptor(newInstance, propertyKey);
427
+ if (strategyProperty?.value !== undefined)
428
+ continue;
429
+ const strategy = await this.resolveStrategy(interfaceName);
430
+ const expression = getOwnTypedMetadata(ComponentConstants.ExpressionKey, classInChain);
431
+ Object.defineProperty(newInstance, propertyKey, {
432
+ get() {
433
+ return expression?.[propertyKey] ? strategy.map((s) => expression[propertyKey](s)) : strategy;
434
+ },
435
+ set: () => {
436
+ throw new TypeError(this.injectedFieldMessage(Class, propertyKey, '@Strategy'));
437
+ },
438
+ enumerable: true,
439
+ configurable: true,
440
+ });
441
+ }
442
+ }
443
+ }
444
+ /**
445
+ * @description Assigns every @Value field of the instance from process.env.
446
+ *
447
+ * Values land as plain writable properties - unlike @Inject fields they hold no
448
+ * resolved service to protect, and tests overwrite them freely. The own-property
449
+ * guard mirrors injectDependencies: a field initializer wins over the environment.
450
+ *
451
+ * @param {any} newInstance - The freshly constructed instance
452
+ * @param {Class} Class - The class of the instance
453
+ * @returns {void}
454
+ */
455
+ injectValues(newInstance, Class) {
456
+ for (const [field, spec] of Object.entries(collectValueFields(Class))) {
457
+ if (Object.getOwnPropertyDescriptor(newInstance, field)?.value !== undefined)
458
+ continue;
459
+ newInstance[field] = readValue(spec, Class, field);
460
+ }
461
+ }
462
+ async injectDependencies(newInstance, Class) {
463
+ const prototypeChain = this.getPrototypeChain(Class);
464
+ for (const classInChain of prototypeChain.reverse()) {
465
+ const deps = getOwnTypedMetadata(ComponentConstants.DependencyKey, classInChain);
466
+ if (!deps)
467
+ continue;
468
+ let property;
469
+ for (const [k, name] of Object.entries(deps)) {
470
+ property = Object.getOwnPropertyDescriptor(newInstance, k);
471
+ if (property?.value !== undefined)
472
+ continue;
473
+ let instance;
474
+ try {
475
+ instance = await this.resolve(name);
476
+ }
477
+ catch (error) {
478
+ // Only the container's own miss, and only once: a nested miss arrives already
479
+ // wrapped in a plain Error, and anything else - CircularDependencyError, a failed
480
+ // hook - must reach the caller unchanged.
481
+ if (error instanceof UnregisteredDependencyError) {
482
+ throw new Error(`'${name}' is not registered (injected into ${Class.name}.${k})`, { cause: error });
483
+ }
484
+ throw error;
485
+ }
486
+ if (instance === null) {
487
+ throw new Error('Instance cant be null ' + name);
488
+ }
489
+ const expression = getOwnTypedMetadata(ComponentConstants.ExpressionKey, classInChain);
490
+ Object.defineProperty(newInstance, k, {
491
+ get: () => {
492
+ return expression?.[k] ? expression[k](instance) : instance;
493
+ },
494
+ set: () => {
495
+ throw new TypeError(this.injectedFieldMessage(Class, k, '@Inject'));
496
+ },
497
+ enumerable: true,
498
+ configurable: true,
499
+ });
500
+ }
501
+ }
502
+ }
503
+ /**
504
+ * The message behind an assignment to a wired field.
505
+ *
506
+ * Injected fields are installed as accessors with no setter, so assigning to one throws the
507
+ * engine's own `TypeError: Attempted to assign to readonly property.` - no field name, no class,
508
+ * no hint at what to do instead. Everybody reaches for `Object.assign(instance, {dep: fake})`
509
+ * once; this turns that minute into a sentence.
510
+ */
511
+ injectedFieldMessage(Class, field, decorator) {
512
+ return (`Cannot assign to '${field}' on ${Class.name}: fields wired by ${decorator} are read-only. ` +
513
+ this.injectedFieldHint);
514
+ }
515
+ /**
516
+ * @description Checks if a class is a framework class (CoreService)
517
+ * Framework classes can traverse the prototype chain even if they contain native code patterns
518
+ * @param {any} cls - The class to check
519
+ * @returns {boolean} True if the class is a framework class
520
+ */
521
+ isFrameworkClass(cls) {
522
+ if (!cls || cls === Object.prototype) {
523
+ return false;
524
+ }
525
+ // Check if class is marked as a CoreService
526
+ const isCoreService = getTypedMetadata(CORE_SERVICE, cls);
527
+ return Boolean(isCoreService);
528
+ }
529
+ /**
530
+ * Deliberately NOT `getPrototypeChainOf` from utils, even though the two overlap.
531
+ *
532
+ * This walk carries two rules the generic helper does not: it bails out at a class whose
533
+ * source reads `[native code]` (so injection never tries to walk into a built-in or a bound
534
+ * constructor), with an escape hatch for `@CoreService` classes, and it returns leaf-first
535
+ * because every caller here reverses it themselves.
536
+ *
537
+ * The generic helper is the right reader for decorator metadata; this one guards instance
538
+ * construction. Merging them would mean picking one set of stop conditions for both.
539
+ */
540
+ getPrototypeChain(Class) {
541
+ const chain = [];
542
+ let currentClass = Class;
543
+ while (currentClass && currentClass !== Object.prototype) {
544
+ const classSource = currentClass.toString();
545
+ const isNativeCode = classSource.includes('[native code]');
546
+ // Stop at native code unless it's a framework class
547
+ if (isNativeCode && !this.isFrameworkClass(currentClass)) {
548
+ break;
549
+ }
550
+ chain.push(currentClass);
551
+ currentClass = Object.getPrototypeOf(currentClass);
552
+ }
553
+ return chain;
554
+ }
555
+ get services() {
556
+ return this._services;
557
+ }
558
+ set services(value) {
559
+ this._services = value;
560
+ this.aliases.clear();
561
+ }
562
+ }
563
+ //# sourceMappingURL=Container.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Container.js","sourceRoot":"","sources":["../../lib/Container.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC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KAAK,CAAC;IACf,CAAC;IAED,IAAW,QAAQ;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,IAAW,QAAQ,CAAC,KAA6D;QAC/E,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;CACF"}
@@ -0,0 +1,88 @@
1
+ import { Container } from './Container';
2
+ import type { LifecycleState } from './lifecycle';
3
+ import type { IocLogger } from './logger';
4
+ import { type Class } from './types';
5
+ /**
6
+ * Options for {@link IocApplication.create}.
7
+ *
8
+ * A non-empty `components` list wins and disables the scan, otherwise `sourceFolder` is
9
+ * scanned. `imports` is always added on top of whichever one applied.
10
+ */
11
+ export interface IocApplicationOptions {
12
+ /** Explicit component classes. When non-empty, `sourceFolder` is not scanned. */
13
+ components?: Class[];
14
+ /**
15
+ * Components handed in by packages, in addition to `components` or the scan. Every entry
16
+ * must carry its own component decorator; the list is flattened one level.
17
+ */
18
+ imports?: (Class | readonly Class[])[];
19
+ /**
20
+ * Folder scanned for decorated classes. A relative path is resolved against the working
21
+ * directory, so a program that can be started from anywhere has to pass an absolute one.
22
+ */
23
+ sourceFolder?: string;
24
+ /**
25
+ * Entry file to keep out of the scan. The running module (`Bun.main`) is always excluded,
26
+ * so this is only needed when the declared entry differs from the file being executed.
27
+ */
28
+ rootFile?: string;
29
+ /** Milliseconds a scanned file may take to import before a warning is logged. 0 disables. */
30
+ importTimeout?: number;
31
+ /** Receives the engine's diagnostics. Defaults to the console, without debug output. */
32
+ logger?: IocLogger;
33
+ /**
34
+ * Values built outside the container, keyed by the name components inject them under:
35
+ * `@Inject('Environment')`. Any value except `null` and `undefined`. They are registered
36
+ * before the components, take no part in the start/stop lifecycle, and a component that
37
+ * claims the same name is an error.
38
+ */
39
+ instances?: Record<string, unknown>;
40
+ /**
41
+ * Test doubles keyed by name, seeded before anything else. The component registered under
42
+ * that name is never constructed, and an entry of `instances` under it is ignored.
43
+ */
44
+ overrides?: Record<string, object>;
45
+ }
46
+ /**
47
+ * The IoC container wired up on its own: container, engine and lifecycle.
48
+ *
49
+ * `create()` registers and constructs every component. Start hooks are deferred until
50
+ * {@link IocApplication.start}, so a hook always sees the finished graph; `stop()` runs the
51
+ * stop hooks in reverse order.
52
+ */
53
+ export declare class IocApplication {
54
+ private readonly _container;
55
+ private readonly engine;
56
+ private readonly lifecycle;
57
+ private constructor();
58
+ /**
59
+ * Build the container and register every component.
60
+ *
61
+ * @param {IocApplicationOptions} options - Component sources, logger, instances and overrides
62
+ * @returns {Promise<IocApplication>} The application, constructed but not started
63
+ */
64
+ static create(options?: IocApplicationOptions): Promise<IocApplication>;
65
+ /**
66
+ * Resolve a component by name or by class.
67
+ *
68
+ * @param {string | Class<T>} key - Component name, or the decorated class
69
+ * @returns {Promise<T>} The component
70
+ */
71
+ resolve<T>(key: string | Class<T>): Promise<T>;
72
+ /**
73
+ * Run every pending start hook, dependencies first.
74
+ *
75
+ * @returns {Promise<void>}
76
+ * @throws When a hook fails, after rolling back the components that already started
77
+ */
78
+ start(): Promise<void>;
79
+ /**
80
+ * Run stop hooks for everything that started, in reverse order.
81
+ *
82
+ * @param {number} hookTimeout - Per-hook ceiling in milliseconds
83
+ * @returns {Promise<number>} How many hooks threw, rejected or ran out of time
84
+ */
85
+ stop(hookTimeout?: number): Promise<number>;
86
+ get container(): Container;
87
+ get state(): LifecycleState;
88
+ }