@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,725 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { ComponentType, ICoreServiceNames, } from './types';
11
+ import { getAllFiles } from './helper/fileHelper';
12
+ import * as path from 'node:path';
13
+ import { ComponentConstants } from './constants';
14
+ import * as process from 'node:process';
15
+ import { getStrategyClass } from './helper/iocHelper';
16
+ import { getOwnTypedMetadata, getTypedMetadata } from './utils/typedMetadata';
17
+ import { getComponentsDeclaredIn, Inject, Scope } from './component';
18
+ import { CoreService } from './decorators';
19
+ import { CircularDependencyError } from './CircularDependencyDetector';
20
+ /**
21
+ * @description IoC Engine - Manages component registration and dependency injection
22
+ * Core service that handles automatic component discovery and registration
23
+ */
24
+ /**
25
+ * @description How long a single component file may take to import before the
26
+ * engine points at it. Only a warning - the import is never cancelled.
27
+ */
28
+ const DEFAULT_IMPORT_TIMEOUT = 10_000;
29
+ let IocEngine = class IocEngine {
30
+ serviceName = 'IocEngine';
31
+ _container;
32
+ logger;
33
+ injectables = [];
34
+ config;
35
+ /** Entry files kept out of the scan, empty unless the scan actually ran */
36
+ entryFiles = new Set();
37
+ /** Entry-declared components that existed by the time the scan ran */
38
+ entryComponents = new Set();
39
+ /**
40
+ * @description Set IoC configuration
41
+ * @param {IocConfig} config - IoC configuration object
42
+ * @returns {void}
43
+ */
44
+ setConfig(config) {
45
+ this.config = config;
46
+ }
47
+ async searchAndRegister(components, imports) {
48
+ // load components
49
+ await this.loadComponents(components, imports);
50
+ this.rejectTakenNames();
51
+ this.reportEmptyStrategyKeys();
52
+ const injectableClasses = this.injectables.map((c) => c.Class);
53
+ // Two-phase registration for PostProcessor support
54
+ const { postProcessorClasses, remainingClasses } = this.separatePostProcessors(injectableClasses);
55
+ // Phase A: Register PostProcessors and their dependencies first (without post-processing)
56
+ if (postProcessorClasses.length > 0) {
57
+ await this.validateAndRegisterComponents(postProcessorClasses);
58
+ // Resolve only actual PostProcessor instances (not their dependencies) and activate them
59
+ for (const cls of postProcessorClasses) {
60
+ const isPostProcessor = getOwnTypedMetadata(ComponentType.POST_PROCESSOR, cls);
61
+ if (isPostProcessor) {
62
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
63
+ const instance = await this._container.resolve(name);
64
+ this._container.registerPostProcessor(instance);
65
+ }
66
+ }
67
+ }
68
+ // Phase B: Register remaining components (post-processing is now active)
69
+ //
70
+ // Their start hooks are held back for LifecycleService to run from start(), so a
71
+ // hook sees the finished graph. Phase A deliberately keeps the old timing: a
72
+ // post-processor's postProcess() reads what its own start hook set up, so deferring it
73
+ // would wrap every component in Phase B against an uninitialised processor.
74
+ if (remainingClasses.length > 0) {
75
+ this._container.setStartHookMode('deferred');
76
+ try {
77
+ await this.validateAndRegisterComponents(remainingClasses);
78
+ }
79
+ finally {
80
+ this._container.setStartHookMode('immediate');
81
+ }
82
+ }
83
+ }
84
+ async loadComponents(components, imports) {
85
+ const importInjectables = this.processImports(imports);
86
+ if (components?.length) {
87
+ // Explicitly listed components go through the same identity check as scanned ones.
88
+ // They used to bypass it entirely, so the own-only rule held for `sourceFolder` apps and
89
+ // not for `components: [...]` ones - and on that path an undecorated subclass still
90
+ // registered under its base's name, overwriting it.
91
+ const listed = components.filter((component) => {
92
+ if (this.isValidComponent(component.Class)) {
93
+ return true;
94
+ }
95
+ this.warnAboutUndecoratedSubclass(component.Class);
96
+ return false;
97
+ });
98
+ if (!listed.length) {
99
+ throw new Error(`None of the ${components.length} class(es) passed as components is a component: ` +
100
+ `${components.map((component) => this.describeClass(component.Class)).join(', ')}. ` +
101
+ 'Each needs a component decorator of its own (@Service, @Component, ...), applied by this copy ' +
102
+ 'of the package - a class decorated through a second installed copy is not recognised.');
103
+ }
104
+ this.injectables = this.dedupeInjectables([...listed, ...importInjectables]);
105
+ return;
106
+ }
107
+ if (!this.config) {
108
+ // Imports alone are a valid component source: a package-only app has no sourceFolder
109
+ // to scan, and silently skipping them would be exactly the failure `imports` prevents
110
+ if (importInjectables.length) {
111
+ this.injectables = this.dedupeInjectables(importInjectables);
112
+ return;
113
+ }
114
+ throw new Error('No components or configuration found');
115
+ }
116
+ const entryFiles = (this.entryFiles = this.resolveEntryFiles());
117
+ // The entry file must not be imported. While it awaits the bootstrap call
118
+ // at module scope it is in the evaluating-async state, so importing it here is a
119
+ // cyclic dynamic import that can only settle once this scan returns - a deadlock
120
+ // (Bun >= 1.3.14 follows the spec and waits, older versions short-circuited it).
121
+ const files = getAllFiles(this.config.sourceFolder).filter((file) => !entryFiles.has(this.toAbsolutePath(file)));
122
+ const scanned = await this.getInjectables(files);
123
+ // Components declared directly in the entry file are still supported: their
124
+ // decorators ran before the bootstrap call, so they come from the registry
125
+ // rather than from a module namespace
126
+ const entryClasses = getComponentsDeclaredIn(entryFiles);
127
+ this.entryComponents = new Set(entryClasses);
128
+ const declaredInEntry = this.processComponents(entryClasses);
129
+ this.injectables = this.dedupeInjectables([
130
+ ...this.injectables,
131
+ ...scanned,
132
+ ...declaredInEntry,
133
+ ...importInjectables,
134
+ ]);
135
+ if (!this.injectables.length) {
136
+ throw new Error('No components found');
137
+ }
138
+ }
139
+ describeClass(candidate) {
140
+ return typeof candidate === 'function' ? candidate.name || '(anonymous class)' : `(${typeof candidate})`;
141
+ }
142
+ /**
143
+ * @description Refuse a component whose name is already held by something registered ahead of
144
+ * the components: one of the container's own services, or a pre-built instance.
145
+ *
146
+ * `Container.register` promotes a key that is registered twice to an array, which is how
147
+ * several implementations share an interface key. Under a component's own name it means
148
+ * every dependent is handed `[instance, component]` instead of either one, so the collision
149
+ * is reported here, before anything is constructed. An overridden name is exempt: there the
150
+ * double replaces the component on purpose.
151
+ * @returns {void}
152
+ * @throws When a component name is already registered
153
+ */
154
+ rejectTakenNames() {
155
+ for (const { Class: component } of this.injectables) {
156
+ const name = getTypedMetadata(ComponentConstants.NameKey, component) || component.name;
157
+ if (!this._container.has(name) || this._container.isOverridden(name)) {
158
+ continue;
159
+ }
160
+ throw new Error(`Component name '${name}' (class ${this.describeClass(component)}) is already registered in the ` +
161
+ 'container - by one of its own services or by a pre-built instance. Give the component another ' +
162
+ "name, e.g. @Service('...').");
163
+ }
164
+ }
165
+ /**
166
+ * @description Report components that were declared in the entry file *after* the
167
+ * bootstrap call. Their decorators had not run yet when the scan read the registry,
168
+ * so they never made it into the container - and without this they would just be
169
+ * quietly missing at runtime.
170
+ * @param {string} bootstrapCall - How the warning names the call that built the container
171
+ * @returns {void}
172
+ */
173
+ warnAboutLateEntryComponents(bootstrapCall = 'IocApplication.create()') {
174
+ if (!this.entryFiles.size) {
175
+ return;
176
+ }
177
+ const late = getComponentsDeclaredIn(this.entryFiles).filter((cls) => !this.entryComponents.has(cls));
178
+ if (!late.length) {
179
+ return;
180
+ }
181
+ this.logger.warn(`[IocEngine] ${late.length} component(s) declared after the ${bootstrapCall} call were not ` +
182
+ `registered: ${late.map((cls) => cls.name).join(', ')}. ` +
183
+ 'Move them above the bootstrap call, or into their own file under sourceFolder.');
184
+ }
185
+ /**
186
+ * @description Absolute paths of the files that must be kept out of the scan:
187
+ * the entry declared in the config, and the module actually being executed.
188
+ * They are usually the same file, but not always - a project may declare one
189
+ * `rootFile` and start another, or run without a config at all.
190
+ * @returns {Set<string>} Resolved absolute entry paths
191
+ */
192
+ resolveEntryFiles() {
193
+ const entryFiles = new Set();
194
+ if (this.config?.rootFile) {
195
+ entryFiles.add(path.resolve(process.cwd(), this.config.rootFile));
196
+ }
197
+ const runningModule = typeof Bun !== 'undefined' ? Bun.main : process.argv[1];
198
+ if (runningModule) {
199
+ entryFiles.add(path.resolve(runningModule));
200
+ }
201
+ return entryFiles;
202
+ }
203
+ /**
204
+ * @description Resolve a scanned path against the working directory. `getAllFiles`
205
+ * mirrors the form of the folder it was given, so a `sourceFolder` configured as an
206
+ * absolute path yields absolute entries that must not be joined onto cwd again.
207
+ * @param {string} file - Path as returned by the scan
208
+ * @returns {string} Absolute path
209
+ */
210
+ toAbsolutePath(file) {
211
+ return path.isAbsolute(file) ? path.normalize(file) : path.resolve(process.cwd(), file);
212
+ }
213
+ /**
214
+ * @description Collapse components that arrived from more than one source - a class
215
+ * re-exported through a barrel file, or one found by both the scan and the registry.
216
+ *
217
+ * Deduplication is by class identity, not by name: `Container.register` promotes a
218
+ * key to an array when the same name is registered twice, which would construct the
219
+ * component a second time (running @PostConstruct again) and hand every dependent an
220
+ * array instead of an instance.
221
+ * @param {InjectableComponent[]} components - Components from every source
222
+ * @returns {InjectableComponent[]} Components with duplicates removed
223
+ */
224
+ dedupeInjectables(components) {
225
+ const seen = new Set();
226
+ const byName = new Map();
227
+ const unique = [];
228
+ for (const component of components) {
229
+ if (seen.has(component.Class))
230
+ continue;
231
+ seen.add(component.Class);
232
+ const name = getTypedMetadata(ComponentConstants.NameKey, component.Class) || component.Class.name;
233
+ const claimed = byName.get(name);
234
+ if (claimed && claimed !== component.Class) {
235
+ // A component name is an identity, so two classes claiming one is a conflict, not a
236
+ // preference. It used to be a warning, and the resolution was silent and arbitrary:
237
+ // `initializeGraph` keyed classes by name in a Map, so whichever came last in scan order
238
+ // won and the other was never registered, and `@Inject(Loser)` returned an instance of
239
+ // the winner. On the explicit `components: [...]` path there was not even a warning.
240
+ throw new Error(`Duplicate component name detected: '${name}' is claimed by both ` +
241
+ `${claimed.name} and ${component.Class.name}. A component name must be unique - ` +
242
+ "give one of them an explicit name, e.g. @Service({ name: '...' }).");
243
+ }
244
+ byName.set(name, component.Class);
245
+ unique.push(component);
246
+ }
247
+ return unique;
248
+ }
249
+ async validateAndRegisterComponents(injectableClasses) {
250
+ const sortedInjectables = this.topologicalSort(injectableClasses, this.injectables);
251
+ await this.register(sortedInjectables);
252
+ }
253
+ async register(injectables) {
254
+ for (const injectable of injectables) {
255
+ const name = getTypedMetadata(ComponentConstants.NameKey, injectable) || injectable.name;
256
+ const isSingleton = getTypedMetadata(ComponentConstants.ScopeKey, injectable) === Scope.SINGLETON;
257
+ if (!isSingleton) {
258
+ this.warnAboutTransientLifecycleHooks(name, injectable);
259
+ }
260
+ const entry = await this._container.register(name, injectable, isSingleton);
261
+ const _interface = getTypedMetadata(ComponentConstants.InterfaceKey, injectable);
262
+ // When `name` is overridden this is the double's entry, so the interface key reaches it too.
263
+ if (_interface && _interface !== name) {
264
+ this._container.registerAlias(_interface, entry);
265
+ }
266
+ }
267
+ }
268
+ /**
269
+ * @description Warn when a transient declares lifecycle hooks.
270
+ *
271
+ * A transient is constructed per resolve and the container keeps no handle on it, so there is
272
+ * nothing for the lifecycle to start or stop. Its @OnStart still runs at construction, but its
273
+ * @OnStop can never run - and a component that acquires something it never releases is worth
274
+ * saying out loud rather than leaving to be discovered as a leak.
275
+ *
276
+ * @param {string} name - Registered component name
277
+ * @param {Class} injectable - The component class
278
+ * @returns {void}
279
+ */
280
+ warnAboutTransientLifecycleHooks(name, injectable) {
281
+ // The container's own walk, not a metadata read: it is the one that de-duplicates an
282
+ // inherited hook and stops at native code, so the two can never disagree about what would
283
+ // have run.
284
+ const stopHooks = this._container.getStopHooks(injectable);
285
+ if (stopHooks.length === 0) {
286
+ return;
287
+ }
288
+ this.logger.warn(`[IocEngine] '${name}' is transient and declares @OnStop (${stopHooks.join(', ')}), which will never ` +
289
+ 'run - the container keeps no handle on a transient instance. Make it a singleton, or release the ' +
290
+ 'resource where it is used.');
291
+ }
292
+ async getInjectables(files) {
293
+ const validFiles = files.filter((file) => file.endsWith('.ts') || file.endsWith('.js') || file.endsWith('.tsx') || file.endsWith('.jsx'));
294
+ const components = await this.importFiles(validFiles);
295
+ return this.processComponents(components);
296
+ }
297
+ async importFiles(files) {
298
+ const timeout = this.config?.importTimeout ?? DEFAULT_IMPORT_TIMEOUT;
299
+ const importPromises = files.map(async (file) => {
300
+ try {
301
+ const module = await this.importFile(this.toAbsolutePath(file), file, timeout);
302
+ return Object.values(module);
303
+ }
304
+ catch (error) {
305
+ // A file inside sourceFolder that cannot be imported used to be skipped, which
306
+ // started the application with that component silently missing - the first symptom
307
+ // being an injection failure much later
308
+ this.logger.error(`[IocEngine] Failed to import component file '${file}':`, error);
309
+ throw new Error(`Failed to import component file '${file}'`, { cause: error });
310
+ }
311
+ });
312
+ const results = await Promise.all(importPromises);
313
+ return results.flat();
314
+ }
315
+ /**
316
+ * @description Import a single component file, pointing at it if it takes suspiciously
317
+ * long. A module whose top-level await never settles would otherwise hang the boot with
318
+ * no output at all; the import itself is left alone, only reported.
319
+ * @param {string} filePath - Absolute path to import
320
+ * @param {string} file - Path as scanned, for the message
321
+ * @param {number} timeout - Milliseconds before warning, 0 disables
322
+ * @returns {Promise<any>} The imported module namespace
323
+ */
324
+ async importFile(filePath, file, timeout) {
325
+ const timer = timeout > 0
326
+ ? setTimeout(() => {
327
+ this.logger.warn(`[IocEngine] Import of '${file}' has not settled after ${timeout}ms. ` +
328
+ 'A top-level await in that file that never resolves will hang startup.');
329
+ }, timeout)
330
+ : undefined;
331
+ try {
332
+ return await import(filePath);
333
+ }
334
+ finally {
335
+ if (timer !== undefined)
336
+ clearTimeout(timer);
337
+ }
338
+ }
339
+ processComponents(components) {
340
+ const valid = [];
341
+ for (const component of components) {
342
+ if (this.isValidComponent(component)) {
343
+ valid.push(component);
344
+ continue;
345
+ }
346
+ this.warnAboutUndecoratedSubclass(component);
347
+ }
348
+ return valid.map((component) => this.createComponentObject(component));
349
+ }
350
+ /**
351
+ * Validates and converts the `imports` list. Unlike scanned or explicitly listed
352
+ * components, an import that carries no decorator of its own is a hard error, not a
353
+ * warning: `warnAboutUndecoratedSubclass` stays silent for a class with no marker
354
+ * anywhere on its chain, and a silently dropped import is exactly the failure the
355
+ * option exists to prevent.
356
+ */
357
+ processImports(imports) {
358
+ if (!imports?.length) {
359
+ return [];
360
+ }
361
+ const injectables = [];
362
+ for (const entry of imports) {
363
+ if (!this.isValidComponent(entry)) {
364
+ throw new Error(this.describeInvalidImport(entry));
365
+ }
366
+ injectables.push(this.createComponentObject(entry));
367
+ }
368
+ return injectables;
369
+ }
370
+ /**
371
+ * The error for an `imports` entry that failed the identity check. A class that extends a
372
+ * component but carries no decorator of its own is told so explicitly: whoever can see
373
+ * `@Service` on the base class reads the generic message as a contradiction.
374
+ * @param {any} entry - The rejected entry
375
+ * @returns {string} The message to throw
376
+ */
377
+ describeInvalidImport(entry) {
378
+ const name = typeof entry === 'function' ? entry.name : String(entry);
379
+ const ancestor = this.findDecoratedAncestor(entry);
380
+ if (ancestor) {
381
+ return (`imports entry ${name} extends the component ${ancestor.name} but carries no decorator of its own - ` +
382
+ `component identity is not inherited. Decorate ${name} (@Service, @Component, ...) or import ` +
383
+ `${ancestor.name} itself if that is what you meant.`);
384
+ }
385
+ return (`imports entry ${name} carries no component decorator - only classes decorated with ` +
386
+ '@Service, @Component, ... can be imported');
387
+ }
388
+ /**
389
+ * @description The nearest class up the prototype chain that carries its own component
390
+ * decorator, or undefined when none does.
391
+ * @param {any} component - A class, or anything else (yields undefined)
392
+ * @returns {Class | undefined} The decorated ancestor
393
+ */
394
+ findDecoratedAncestor(component) {
395
+ if (typeof component !== 'function') {
396
+ return undefined;
397
+ }
398
+ let ancestor = Object.getPrototypeOf(component);
399
+ while (typeof ancestor === 'function' && ancestor !== Function.prototype) {
400
+ if (getOwnTypedMetadata(ComponentConstants.IOCObjectKey, ancestor)) {
401
+ return ancestor;
402
+ }
403
+ ancestor = Object.getPrototypeOf(ancestor);
404
+ }
405
+ return undefined;
406
+ }
407
+ /**
408
+ * Reports a class that extends a component but carries no decorator of its own.
409
+ *
410
+ * Component identity is read own-only, so such a class is simply skipped. Registering it
411
+ * under its *base's* name blew up on first inject - ugly, but at least detectable. Skipping
412
+ * it silently is worse: whatever the class was meant to do never happens and nothing
413
+ * anywhere says so.
414
+ *
415
+ * Only fires when an ancestor carries the marker, so an ordinary undecorated helper class in
416
+ * the scan folder stays quiet. A decorator that returns a wrapper subclass and applies
417
+ * `@Service` to the wrapper gives the wrapper its own marker, so it never reaches here.
418
+ */
419
+ warnAboutUndecoratedSubclass(component) {
420
+ const ancestor = this.findDecoratedAncestor(component);
421
+ if (!ancestor) {
422
+ return;
423
+ }
424
+ this.logger.warn(`[IocEngine] '${component.name}' extends the component '${ancestor.name}' but carries no decorator of ` +
425
+ 'its own, so it was NOT registered. Decorate it (@Service, @Component, ...) or remove it ' +
426
+ 'from the scan folder.');
427
+ }
428
+ isValidComponent(component) {
429
+ try {
430
+ // Own-only. A class is whatever its OWN decorator says it is - component identity is not
431
+ // inherited. Reading this off the chain made an *undecorated* subclass a component, and
432
+ // since NameKey is read the same way it registered under its base's name: the container
433
+ // promoted the entry to an array and every @Inject(Base) started returning [Base, Sub].
434
+ return !!getOwnTypedMetadata(ComponentConstants.IOCObjectKey, component);
435
+ }
436
+ catch {
437
+ return false;
438
+ }
439
+ }
440
+ createComponentObject(component) {
441
+ return {
442
+ Class: component,
443
+ interface: getTypedMetadata(ComponentConstants.InterfaceKey, component),
444
+ };
445
+ }
446
+ topologicalSort(classes, injectables) {
447
+ const inDegree = new Map();
448
+ const adjacencyList = new Map();
449
+ const nameToClass = new Map();
450
+ this.initializeGraph(classes, injectables, inDegree, adjacencyList, nameToClass);
451
+ const queue = [];
452
+ inDegree.forEach((degree, node) => {
453
+ if (degree === 0)
454
+ queue.push(node);
455
+ });
456
+ const sorted = [];
457
+ let visitedCount = 0;
458
+ while (queue.length > 0) {
459
+ const currentNode = queue.shift();
460
+ visitedCount++;
461
+ const currentClass = nameToClass.get(currentNode);
462
+ if (currentClass) {
463
+ sorted.push(currentClass);
464
+ }
465
+ const neighbors = adjacencyList.get(currentNode) || [];
466
+ for (const neighbor of neighbors) {
467
+ const newDegree = inDegree.get(neighbor) - 1;
468
+ inDegree.set(neighbor, newDegree);
469
+ if (newDegree === 0) {
470
+ queue.push(neighbor);
471
+ }
472
+ }
473
+ }
474
+ if (visitedCount !== inDegree.size) {
475
+ const cycle = this.findCycle(adjacencyList);
476
+ throw new CircularDependencyError(`Circular dependency detected: ${cycle.join(' -> ')}`);
477
+ }
478
+ return sorted.reverse();
479
+ }
480
+ initializeGraph(classes, injectables, inDegree, adjacencyList, nameToClass) {
481
+ classes.forEach((cls) => {
482
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
483
+ nameToClass.set(name, cls);
484
+ inDegree.set(name, 0);
485
+ adjacencyList.set(name, []);
486
+ });
487
+ classes.forEach((cls) => {
488
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
489
+ const dependencies = [
490
+ ...this.getDependencies(cls).flatMap((dep) => this.expandInterfaceDependency(dep, name, nameToClass, injectables)),
491
+ ...this.getStrategyDependencies(cls, injectables),
492
+ ];
493
+ dependencies.forEach((dep) => {
494
+ if (dep) {
495
+ adjacencyList.get(name)?.push(dep);
496
+ inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
497
+ }
498
+ });
499
+ });
500
+ }
501
+ /**
502
+ * `@Inject('IMailer')` names an `@Implements` interface key, not a component, so it has no node
503
+ * in the graph. Its implementations are the components that must be registered first.
504
+ */
505
+ expandInterfaceDependency(dep, selfName, nameToClass, injectables) {
506
+ // An overridden interface key already holds its double; ordering the real classes could only add false cycles.
507
+ if (!dep || nameToClass.has(dep) || this._container.isOverridden(dep)) {
508
+ return [dep];
509
+ }
510
+ const implementations = getStrategyClass({ dep }, injectables).filter((implementation) => implementation && implementation !== selfName);
511
+ return implementations.length ? implementations : [dep];
512
+ }
513
+ findCycle(adjacencyList) {
514
+ const visited = new Set();
515
+ const recStack = new Set();
516
+ const cycle = [];
517
+ const dfs = (node) => {
518
+ if (recStack.has(node)) {
519
+ cycle.push(node);
520
+ return true;
521
+ }
522
+ if (visited.has(node))
523
+ return false;
524
+ visited.add(node);
525
+ recStack.add(node);
526
+ const neighbors = adjacencyList.get(node) || [];
527
+ for (const neighbor of neighbors) {
528
+ if (dfs(neighbor)) {
529
+ if (cycle[0] !== cycle[cycle.length - 1]) {
530
+ cycle.push(node);
531
+ }
532
+ return true;
533
+ }
534
+ }
535
+ recStack.delete(node);
536
+ return false;
537
+ };
538
+ for (const node of adjacencyList.keys()) {
539
+ if (dfs(node))
540
+ break;
541
+ }
542
+ return cycle.reverse();
543
+ }
544
+ /**
545
+ * @description Separates PostProcessor classes and their transitive dependencies from other components.
546
+ * PostProcessors and their deps are registered in Phase A (before post-processing is active).
547
+ * Non-PostProcessor dependencies pulled into Phase A will NOT be post-processed (by design).
548
+ */
549
+ separatePostProcessors(classes) {
550
+ // Find all PostProcessor classes
551
+ const postProcessorSet = new Set();
552
+ const nameToClass = new Map();
553
+ for (const cls of classes) {
554
+ const name = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
555
+ nameToClass.set(name, cls);
556
+ }
557
+ // Identify PostProcessor classes
558
+ for (const cls of classes) {
559
+ if (getOwnTypedMetadata(ComponentType.POST_PROCESSOR, cls)) {
560
+ postProcessorSet.add(cls);
561
+ }
562
+ }
563
+ if (postProcessorSet.size === 0) {
564
+ return { postProcessorClasses: [], remainingClasses: classes };
565
+ }
566
+ // Compute transitive dependency closure for all PostProcessors
567
+ const closureSet = new Set(postProcessorSet);
568
+ const addDependencyClosure = (cls) => {
569
+ const deps = [...this.getDependencies(cls), ...this.getStrategyDependencies(cls, this.injectables)];
570
+ for (const depName of deps) {
571
+ const depClass = nameToClass.get(depName);
572
+ if (depClass && !closureSet.has(depClass)) {
573
+ closureSet.add(depClass);
574
+ // Log warning for non-PostProcessor dependencies pulled into Phase A
575
+ if (!getOwnTypedMetadata(ComponentType.POST_PROCESSOR, depClass)) {
576
+ const ppName = getTypedMetadata(ComponentConstants.NameKey, cls) || cls.name;
577
+ this.logger.warn(`[IocEngine] PostProcessor '${ppName}' depends on '${depName}'. ${depName} will not be post-processed.`);
578
+ }
579
+ // Recurse into this dependency's own dependencies
580
+ addDependencyClosure(depClass);
581
+ }
582
+ }
583
+ };
584
+ for (const ppClass of postProcessorSet) {
585
+ addDependencyClosure(ppClass);
586
+ }
587
+ // Split into two groups
588
+ const postProcessorClasses = [];
589
+ const remainingClasses = [];
590
+ for (const cls of classes) {
591
+ if (closureSet.has(cls)) {
592
+ postProcessorClasses.push(cls);
593
+ }
594
+ else {
595
+ remainingClasses.push(cls);
596
+ }
597
+ }
598
+ return { postProcessorClasses, remainingClasses };
599
+ }
600
+ getDependencies(component) {
601
+ try {
602
+ const directDependencies = Object.values(getOwnTypedMetadata(ComponentConstants.DependencyKey, component) || {});
603
+ const softDependencies = Object.values(getOwnTypedMetadata(ComponentConstants.SoftDependencyKey, component) || {});
604
+ const parentClass = Object.getPrototypeOf(component);
605
+ if (parentClass &&
606
+ parentClass !== Object.prototype &&
607
+ // circular detection
608
+ parentClass.toString() !== 'function () {\n' + ' [native code]\n' + '}') {
609
+ const parentDependencies = this.getDependencies(parentClass);
610
+ const parentName = getTypedMetadata(ComponentConstants.NameKey, parentClass) || parentClass.name;
611
+ const selfName = getTypedMetadata(ComponentConstants.NameKey, component) || component.name;
612
+ // A decorator may return a subclass of the class it decorates and register the
613
+ // subclass under the decorated class's own name.
614
+ // The parent then resolves to the component's own name, which is not a cycle -
615
+ // reporting it as one made the component unresolvable.
616
+ const parentEntry = parentName && parentName !== selfName ? [parentName] : [];
617
+ return [
618
+ ...new Set([
619
+ ...directDependencies,
620
+ ...parentDependencies,
621
+ ...softDependencies,
622
+ // Parent is registered as a soft dep so subclasses are created after it
623
+ ...parentEntry,
624
+ ]),
625
+ ];
626
+ }
627
+ return [...new Set([...directDependencies, ...softDependencies])];
628
+ }
629
+ catch {
630
+ return [];
631
+ }
632
+ }
633
+ /**
634
+ * Every strategy key a component consumes, keyed by the field that declares it. Walks the
635
+ * prototype chain like getStrategyDependencies does - a @Strategy field on a base class is
636
+ * injected into the subclass too, so it has to be reported against the subclass. Own class
637
+ * first, so a field redeclared in a subclass wins the same way injection resolves it.
638
+ */
639
+ collectStrategyFields(component) {
640
+ const fields = new Map();
641
+ const own = getOwnTypedMetadata(ComponentConstants.StrategyKey, component);
642
+ for (const [field, key] of Object.entries(own ?? {})) {
643
+ if (typeof key === 'string' && key) {
644
+ fields.set(field, key);
645
+ }
646
+ }
647
+ const parent = Object.getPrototypeOf(component);
648
+ if (typeof parent === 'function' && parent !== Function.prototype) {
649
+ for (const [field, key] of this.collectStrategyFields(parent)) {
650
+ if (!fields.has(field)) {
651
+ fields.set(field, key);
652
+ }
653
+ }
654
+ }
655
+ return fields;
656
+ }
657
+ /**
658
+ * Reports strategy keys nothing implements, once per injection site, at boot.
659
+ *
660
+ * An empty key is a legitimate plugin point and is injected as `[]`, which means a *typo'd*
661
+ * interface name no longer fails at boot either - it surfaces much later as a collection
662
+ * that is silently always empty. This line is what keeps the two apart.
663
+ *
664
+ * `debug` with no fallback to `info`, deliberately: a deliberate plugin point should stay
665
+ * quiet unless someone is looking.
666
+ */
667
+ reportEmptyStrategyKeys() {
668
+ // Optional twice over: `debug` is optional on IocLogger, and `logger` itself is absent
669
+ // whenever an IocEngine is built directly instead of through DI - which several suites do.
670
+ // A diagnostic must not be the thing that decides whether registration runs. The warn/error
671
+ // paths elsewhere stay unguarded, so genuinely broken wiring still fails loudly.
672
+ const debug = this.logger?.debug;
673
+ if (!debug) {
674
+ return;
675
+ }
676
+ const implemented = new Set(this.injectables.map((injectable) => injectable.interface).filter(Boolean));
677
+ for (const { Class: component } of this.injectables) {
678
+ const name = getTypedMetadata(ComponentConstants.NameKey, component) || component.name;
679
+ for (const [field, key] of this.collectStrategyFields(component)) {
680
+ // A double seeded through `overrides` is a real implementation of that key - warning
681
+ // here would fire on every slice test that mocks a plugin point
682
+ if (implemented.has(key) || this._container.isOverridden(key)) {
683
+ continue;
684
+ }
685
+ debug.call(this.logger, `[IocEngine] Strategy key '${key}' has no implementations - ${name}.${field} will be injected as []`);
686
+ }
687
+ }
688
+ }
689
+ getStrategyDependencies(component, injectables) {
690
+ try {
691
+ const strategyMeta = getOwnTypedMetadata(ComponentConstants.StrategyKey, component);
692
+ const directStrategies = getStrategyClass(strategyMeta, injectables);
693
+ const parentClass = Object.getPrototypeOf(component);
694
+ // Recurse on the parent class itself. This used to recurse on
695
+ // `parentClass.constructor`, which for a class is always `Function` - so the walk
696
+ // stopped at the first level and a @Strategy field declared on a base class was
697
+ // missing from the dependency graph. The component then resolved before the
698
+ // implementations it needed were registered ("<interface> is not registered").
699
+ if (typeof parentClass === 'function' && parentClass !== Function.prototype) {
700
+ const parentStrategies = this.getStrategyDependencies(parentClass, injectables);
701
+ return [...new Set([...directStrategies, ...parentStrategies])];
702
+ }
703
+ return directStrategies;
704
+ }
705
+ catch {
706
+ return [];
707
+ }
708
+ }
709
+ get container() {
710
+ return this._container;
711
+ }
712
+ };
713
+ __decorate([
714
+ Inject('Container'),
715
+ __metadata("design:type", Function)
716
+ ], IocEngine.prototype, "_container", void 0);
717
+ __decorate([
718
+ Inject(ICoreServiceNames.LOGGER),
719
+ __metadata("design:type", Object)
720
+ ], IocEngine.prototype, "logger", void 0);
721
+ IocEngine = __decorate([
722
+ CoreService(ICoreServiceNames.IOC_ENGINE)
723
+ ], IocEngine);
724
+ export { IocEngine };
725
+ //# sourceMappingURL=IocEngine.js.map