@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AsenaJs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,220 @@
1
- # Temporary Holding Version
1
+ <p width="%100" align="center">
2
+ <img src="https://avatars.githubusercontent.com/u/179836938?s=200&v=4" width="150" align="center"/>
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # @asenajs/ioc
6
+
7
+ [![Version](https://img.shields.io/npm/v/@asenajs/ioc.svg)](https://github.com/AsenaJs/ioc)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
9
+ [![Bun Version](https://img.shields.io/badge/Bun-1.4%2B-blueviolet)](https://bun.sh)
10
+
11
+ An IoC container for Bun: components declared with decorators, field-based dependency injection,
12
+ and a start/stop lifecycle. It knows nothing about what the components are for - a CLI, a worker
13
+ and a framework all sit on the same container.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ bun add @asenajs/ioc
19
+ ```
20
+
21
+ ## Requirements
22
+
23
+ - Bun >= 1.4
24
+ - A `tsconfig.json` with `experimentalDecorators` enabled. `emitDecoratorMetadata` is not needed:
25
+ every injection names its dependency explicitly.
26
+
27
+ Bun 1.4.5 picks the decorator dialect for TypeScript it runs from source from the `tsconfig.json`
28
+ in the working directory, not from the one beside the file. Run from anywhere else, the same
29
+ source gets standard decorators, and the first `@Inject`, `@Strategy`, `@Value`, `@OnStart` or
30
+ `@OnStop` throws an error that says so. Anything started from another directory has to ship built
31
+ output (`tsc`, `bun build` or `bun build --compile`), where the decorators are already compiled,
32
+ or be started with `bun --tsconfig-override=<path>`.
33
+
34
+ ## Usage
35
+
36
+ ```typescript
37
+ import { Inject, IocApplication, OnStart, OnStop, Service } from '@asenajs/ioc';
38
+
39
+ @Service()
40
+ class Database {
41
+ @OnStart()
42
+ public open(): void {}
43
+
44
+ @OnStop()
45
+ public close(): void {}
46
+ }
47
+
48
+ @Service()
49
+ class UserService {
50
+ @Inject(Database)
51
+ private database: Database;
52
+ }
53
+
54
+ const app = await IocApplication.create({ components: [Database, UserService] });
55
+
56
+ await app.start();
57
+
58
+ const users = await app.resolve(UserService);
59
+
60
+ await app.stop();
61
+ ```
62
+
63
+ `create()` constructs every singleton and wires its fields. Their start hooks are held back until
64
+ `start()`, so a hook sees the finished graph; `stop()` runs the stop hooks in reverse order.
65
+
66
+ Three kinds of component run their start hooks at construction instead: a `@PostProcessor`, the
67
+ components it depends on, and anything with `Scope.PROTOTYPE`. A prototype-scoped component is
68
+ built per resolve and never stopped.
69
+
70
+ Components are constructed with `new Class()` and no arguments, and their fields are wired after
71
+ the constructor returns: an injected field is `undefined` inside the constructor and in a field
72
+ initializer. Work that needs a dependency belongs in an `@OnStart` method. A class that takes
73
+ constructor arguments is not a component - build it with `new` where it is used.
74
+
75
+ ## Component sources
76
+
77
+ | Option | Behaviour |
78
+ | -------------- | ------------------------------------------------------------------------------------------------------ |
79
+ | `components` | Explicit classes. When non-empty, nothing is scanned and the file system is never touched. A list in which no class is a component fails `create()`. |
80
+ | `sourceFolder` | Folder scanned for decorated classes, plus those declared in the entry file above the `create()` call. |
81
+ | `imports` | Always added on top of whichever of the two applied. |
82
+
83
+ ```typescript
84
+ const app = await IocApplication.create({ sourceFolder: 'src' });
85
+ ```
86
+
87
+ The scan imports every `.ts`/`.js` file under the folder, so the folder has to exist at runtime
88
+ and hold nothing that must not run. A relative `sourceFolder` is resolved against the working
89
+ directory.
90
+
91
+ ### Command-line programs
92
+
93
+ Use `components`. It is the only source that works in every way a CLI is shipped:
94
+
95
+ | Shipped as | `components` | `sourceFolder` |
96
+ | ----------------------------------- | ------------ | ------------------------------------------------------------------------- |
97
+ | `tsc` output, installed as a `bin` | works | only with an absolute path (`import.meta.dir`); `'src'` is the user's src |
98
+ | `bun build` bundle | works | no source files to scan |
99
+ | `bun build --compile` binary | works | no source files to scan |
100
+
101
+ A CLI started in somebody else's project that scans a relative folder imports *their* files.
102
+
103
+ ```typescript
104
+ @Service()
105
+ @Implements('Command')
106
+ class BuildCommand {
107
+ public command(): Command { ... }
108
+ }
109
+
110
+ @Service()
111
+ class Cli {
112
+ @Strategy('Command')
113
+ private commands: { command: () => Command }[];
114
+ }
115
+
116
+ const app = await IocApplication.create({ components: [Cli, BuildCommand] });
117
+ ```
118
+
119
+ `--help`, `--version` and a `process.exit()` inside a command end the process before `stop()`
120
+ runs. Parse in a `try`/`finally` around `stop()`, and let the parser throw instead of exiting
121
+ (`exitOverride()` in commander).
122
+
123
+ ### Names and minification
124
+
125
+ A component is registered under the name given to its decorator, or under its class name. Minifying
126
+ identifiers renames classes, so with `bun build --minify`:
127
+
128
+ - `@Inject(UserService)` and `app.resolve(UserService)` keep working - the name is read from the
129
+ class, whatever it became.
130
+ - `@Inject('UserService')`, `app.resolve('UserService')` and `overrides: { UserService: ... }` only
131
+ work when the component was named explicitly: `@Service('UserService')`.
132
+
133
+ `--minify-whitespace --minify-syntax` leaves names alone.
134
+
135
+ ## Decorators
136
+
137
+ | Decorator | Purpose |
138
+ | ----------------------------- | ---------------------------------------------------------- |
139
+ | `@Service()` / `@Component()` | Mark a class as a component. Singleton unless scoped. |
140
+ | `@Inject(ClassOrName)` | Inject a single dependency into a field. |
141
+ | `@Implements('Key')` | Register the component under an interface key as well. |
142
+ | `@Strategy('Key')` | Inject every implementation of an interface key, as array. |
143
+ | `@Value('ENV_NAME', options)` | Inject a value from `process.env`. |
144
+ | `@OnStart()` / `@OnStop()` | Lifecycle hooks, run by `start()` and `stop()`. |
145
+ | `@PostProcessor()` | Inspect or wrap every component after it is constructed. |
146
+
147
+ ## Pre-built instances
148
+
149
+ Values that are built outside the container - the environment, a clock, parsed arguments - go in
150
+ by name through `instances` and are injected like any component:
151
+
152
+ ```typescript
153
+ @Service()
154
+ class DeployCommand {
155
+ @Inject('Environment')
156
+ private environment: NodeJS.ProcessEnv;
157
+
158
+ @Inject('Now')
159
+ private now: () => number;
160
+ }
161
+
162
+ const app = await IocApplication.create({
163
+ components: [DeployCommand],
164
+ instances: { Environment: process.env, Now: Date.now, Verbose: false },
165
+ });
166
+ ```
167
+
168
+ - Any value except `null` and `undefined` is accepted: objects, functions, strings, numbers,
169
+ booleans, arrays. An optional value is left out of the record, not registered as `undefined`.
170
+ - Instances are registered before the components and are never started or stopped: whoever built
171
+ one owns its lifetime.
172
+ - A component that claims the name of an instance, or of one of the container's own services,
173
+ fails `create()`.
174
+
175
+ ## Test doubles
176
+
177
+ ```typescript
178
+ const app = await IocApplication.create({
179
+ components: [Database, UserService],
180
+ instances: { Now: Date.now },
181
+ overrides: { Database: fakeDatabase, Now: () => 0 },
182
+ });
183
+ ```
184
+
185
+ `overrides` replaces whatever is registered under a name. A component under an overridden name is
186
+ never constructed, an instance under it is ignored, and every dependent receives the double.
187
+ Overrides have to be objects or functions.
188
+
189
+ ## The container's own services
190
+
191
+ Registered by `IocApplication` under these names and injectable like any component:
192
+
193
+ | `ICoreServiceNames` | Name | What |
194
+ | ------------------- | -------------------- | ---------------------------------------- |
195
+ | `CONTAINER` | `'Container'` | The `Container` itself. |
196
+ | `LOGGER` | `'IocLogger'` | The `logger` option, or the console. |
197
+ | `IOC_ENGINE` | `'IocEngine'` | Discovers and registers components. |
198
+ | `LIFECYCLE_SERVICE` | `'LifecycleService'` | Runs the start and stop hooks. |
199
+
200
+ ## Building on the container
201
+
202
+ `IocApplication` is one way to wire the pieces; a framework that needs more registers them itself
203
+ and drives `Container`, `IocEngine` and `LifecycleService` directly.
204
+
205
+ - **Component kinds.** `defineComponent(kind, params, extra)` is what `@Service` is made of. The
206
+ kind is any string or symbol, and `container.resolveAll(kind)` returns every component of it. A
207
+ string `params` is the component name; a decorator whose string argument means something else
208
+ passes an object.
209
+ - **Metadata keys.** `ComponentConstants` is a class of static symbols, so `class MyConstants
210
+ extends ComponentConstants` keeps a framework's keys beside the container's. The keys are plain
211
+ `Symbol()`s: two installed copies of this package do not see each other's components, so a
212
+ framework re-exporting these decorators should depend on the package as a peer.
213
+ - **Core services.** `@CoreService(name)` marks infrastructure that is registered by hand with
214
+ `container.register(name, Class, true)` before the components that inject it.
215
+ - **Wrapping decorators.** A decorator that wraps the one `defineComponent` returns in its own
216
+ function must call `skipDeclarationFramesUnder(directory)` once for the directory it lives in,
217
+ or components declared in the entry file are attributed to it and not found.
218
+ - **Wording.** `warnAboutLateEntryComponents(bootstrapCall)` and the protected
219
+ `Container.injectedFieldHint` let the framework name its own entry point and test utilities in
220
+ the two messages that would otherwise name `IocApplication`.
@@ -0,0 +1 @@
1
+ export * from './lib';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './lib';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @description Custom error class for circular dependency detection
3
+ * Provides detailed information about the circular dependency chain
4
+ */
5
+ export declare class CircularDependencyError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ /**
9
+ * @description Detector for circular dependencies in the IoC container
10
+ * Tracks the resolution stack and detects cycles during dependency injection
11
+ */
12
+ export declare class CircularDependencyDetector {
13
+ private resolutionStack;
14
+ /**
15
+ * @description Check if service creates circular dependency
16
+ * @param {string} serviceName - The service being resolved
17
+ * @throws {CircularDependencyError} If circular dependency is detected
18
+ * @returns {void}
19
+ */
20
+ checkCircular(serviceName: string): void;
21
+ /**
22
+ * @description Push service to resolution stack
23
+ * @param {string} serviceName - The service being resolved
24
+ * @returns {void}
25
+ */
26
+ push(serviceName: string): void;
27
+ /**
28
+ * @description Pop service from resolution stack
29
+ * @param {string} serviceName - The service that was resolved
30
+ * @returns {void}
31
+ */
32
+ pop(serviceName: string): void;
33
+ /**
34
+ * @description Clear the resolution stack
35
+ * Useful for testing or manual stack reset
36
+ * @returns {void}
37
+ */
38
+ clear(): void;
39
+ /**
40
+ * @description Get current resolution stack as array
41
+ * @returns {string[]} Array of service names in resolution order
42
+ */
43
+ getStack(): string[];
44
+ /**
45
+ * @description Check if stack is empty
46
+ * @returns {boolean}
47
+ */
48
+ isEmpty(): boolean;
49
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @description Custom error class for circular dependency detection
3
+ * Provides detailed information about the circular dependency chain
4
+ */
5
+ export class CircularDependencyError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'CircularDependencyError';
9
+ }
10
+ }
11
+ /**
12
+ * @description Detector for circular dependencies in the IoC container
13
+ * Tracks the resolution stack and detects cycles during dependency injection
14
+ */
15
+ export class CircularDependencyDetector {
16
+ resolutionStack = new Set();
17
+ /**
18
+ * @description Check if service creates circular dependency
19
+ * @param {string} serviceName - The service being resolved
20
+ * @throws {CircularDependencyError} If circular dependency is detected
21
+ * @returns {void}
22
+ */
23
+ checkCircular(serviceName) {
24
+ if (this.resolutionStack.has(serviceName)) {
25
+ const stack = Array.from(this.resolutionStack);
26
+ const chain = [...stack, serviceName].join(' -> ');
27
+ throw new CircularDependencyError(`Circular dependency detected: ${chain}`);
28
+ }
29
+ }
30
+ /**
31
+ * @description Push service to resolution stack
32
+ * @param {string} serviceName - The service being resolved
33
+ * @returns {void}
34
+ */
35
+ push(serviceName) {
36
+ this.resolutionStack.add(serviceName);
37
+ }
38
+ /**
39
+ * @description Pop service from resolution stack
40
+ * @param {string} serviceName - The service that was resolved
41
+ * @returns {void}
42
+ */
43
+ pop(serviceName) {
44
+ this.resolutionStack.delete(serviceName);
45
+ }
46
+ /**
47
+ * @description Clear the resolution stack
48
+ * Useful for testing or manual stack reset
49
+ * @returns {void}
50
+ */
51
+ clear() {
52
+ this.resolutionStack.clear();
53
+ }
54
+ /**
55
+ * @description Get current resolution stack as array
56
+ * @returns {string[]} Array of service names in resolution order
57
+ */
58
+ getStack() {
59
+ return Array.from(this.resolutionStack);
60
+ }
61
+ /**
62
+ * @description Check if stack is empty
63
+ * @returns {boolean}
64
+ */
65
+ isEmpty() {
66
+ return this.resolutionStack.size === 0;
67
+ }
68
+ }
69
+ //# sourceMappingURL=CircularDependencyDetector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CircularDependencyDetector.js","sourceRoot":"","sources":["../../lib/CircularDependencyDetector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAChD,YAAmB,OAAe;QAChC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,0BAA0B;IAC7B,eAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;IAEjD;;;;;OAKG;IACI,aAAa,CAAC,WAAmB;QACtC,IAAI,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YAC/C,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK,EAAE,WAAW,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAEnD,MAAM,IAAI,uBAAuB,CAAC,iCAAiC,KAAK,EAAE,CAAC,CAAC;QAC9E,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,IAAI,CAAC,WAAmB;QAC7B,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAC,WAAmB;QAC5B,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IAED;;;;OAIG;IACI,KAAK;QACV,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED;;;OAGG;IACI,QAAQ;QACb,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAC1C,CAAC;IAED;;;OAGG;IACI,OAAO;QACZ,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,KAAK,CAAC,CAAC;IACzC,CAAC;CACF"}
@@ -0,0 +1,247 @@
1
+ import type { Class, ComponentKind, ComponentPostProcessor, ContainerService, LifecycleComponent, StartHookMode } from './types';
2
+ /**
3
+ * Thrown by {@link Container.resolve} when the requested key has no registration.
4
+ *
5
+ * Carries no information about who needed the key - `resolve` cannot know that - so
6
+ * `injectDependencies` catches it and rethrows with the dependent class and field attached.
7
+ * The subclass identity is what tells an unwrapped miss (wrap it) from any other failure
8
+ * (rethrow untouched), including an already-wrapped nested miss.
9
+ */
10
+ export declare class UnregisteredDependencyError extends Error {
11
+ constructor(message: string);
12
+ }
13
+ export declare class Container {
14
+ private _services;
15
+ private circularDetector;
16
+ private postProcessors;
17
+ private overriddenKeys;
18
+ /** Key -> entries that live there only as an alias of their own key (see `registerAlias`). */
19
+ private aliases;
20
+ /**
21
+ * How the error for an assignment to a wired field ends: what to do instead. Whatever wraps
22
+ * the container names its own way of seeding a test double here.
23
+ */
24
+ protected injectedFieldHint: string;
25
+ /**
26
+ * Whether construction runs start hooks itself.
27
+ *
28
+ * `immediate` is the original behaviour and stays that way for core services, for the
29
+ * post-processor closure the IoC engine registers ahead of everything else, and for every
30
+ * transient. `deferred` holds the hooks back so `LifecycleService` can run them from
31
+ * `start()`, once the whole graph exists.
32
+ */
33
+ private startHookMode;
34
+ /**
35
+ * Every singleton built by `register()`, in registration order - which the IoC engine has
36
+ * already topologically sorted, so dependencies come before dependents. Start hooks walk it
37
+ * forwards, stop hooks backwards.
38
+ *
39
+ * Instances handed in through `registerInstance()` are deliberately absent: nothing ever ran
40
+ * a start hook on them, so there is no started/stopped pair to keep symmetric.
41
+ */
42
+ private lifecycleComponents;
43
+ constructor(services?: {
44
+ [key: string]: ContainerService | ContainerService[];
45
+ });
46
+ /**
47
+ * @returns {Promise<ContainerService>} The new entry, or the test double's entry when `key` is overridden
48
+ */
49
+ register(key: string, Class: Class, singleton: boolean): Promise<ContainerService>;
50
+ /**
51
+ * @description Make an entry registered under one key reachable under another as well.
52
+ *
53
+ * The entry object itself is shared, so a singleton keeps one instance and one lifecycle no
54
+ * matter how many keys reach it - `@Implements` registers a component under its name and its
55
+ * interface key this way. Component scans (`resolveAll`) skip alias positions, so the
56
+ * component is still found exactly once.
57
+ *
58
+ * @param {string} key - The additional key, e.g. an `@Implements` interface name
59
+ * @param {ContainerService} entry - An entry returned by `register()`
60
+ * @returns {void}
61
+ */
62
+ registerAlias(key: string, entry: ContainerService): void;
63
+ private store;
64
+ /**
65
+ * @description Record a singleton for the start/stop lifecycle.
66
+ *
67
+ * `started` reflects what already happened rather than what is planned: a component built in
68
+ * immediate mode has run its start hooks by the time it gets here, so it is stoppable at once.
69
+ * A deferred one is not started until `LifecycleService` says so - and a component that never
70
+ * started must never be stopped.
71
+ *
72
+ * @param {string} key - Service identifier
73
+ * @param {unknown} instance - The post-processed instance
74
+ * @param {Class} Class - The class it was built from
75
+ * @returns {void}
76
+ */
77
+ private trackLifecycle;
78
+ /**
79
+ * @description Register an already-created instance directly
80
+ * Useful for dependencies created outside the container, like the logger. Any value except
81
+ * `null` and `undefined` can be registered, including `0`, `''`, `false` and an empty array.
82
+ * @param {string} key - Service identifier
83
+ * @param {T} instance - Pre-created instance
84
+ * @returns {Promise<void>}
85
+ */
86
+ registerInstance<T>(key: string, instance: T): Promise<void>;
87
+ /**
88
+ * @description Replace a service with a pre-created test double (Spring's @MockBean).
89
+ *
90
+ * Seeds the container before user components are registered: any later `register()`
91
+ * call for the same key becomes a no-op, so the real class is never constructed and
92
+ * dependents capture the override in their injection closures.
93
+ *
94
+ * @param {string} key - Service identifier to override
95
+ * @param {T} instance - Replacement instance
96
+ * @returns {void}
97
+ */
98
+ overrideInstance<T>(key: string, instance: T): void;
99
+ /**
100
+ * @description Check whether a key has been replaced by an override
101
+ * @param {string} key - Service key
102
+ * @returns {boolean}
103
+ */
104
+ isOverridden(key: string): boolean;
105
+ resolve<T>(key: string): Promise<(T | T[]) | null>;
106
+ /**
107
+ * @description Check if a service is registered without resolving it
108
+ * @param {string} key - Service key
109
+ * @returns {boolean}
110
+ */
111
+ has(key: string): boolean;
112
+ /**
113
+ * @description Resolve every implementation registered under a strategy key.
114
+ *
115
+ * Cardinality is normalized here rather than borrowed from resolve(). `_services[key]` has
116
+ * three shapes - absent, a bare ContainerService, an array - and resolve() maps them to
117
+ * throw / T / T[]. That is right for @Inject, whose dependency is single-valued: it is
118
+ * either there or the component is broken. @Strategy is multi-valued by construction, so
119
+ * zero is a cardinality it has to be able to take (a plugin point before its first plugin)
120
+ * and one has to arrive as a one-element array like any other count.
121
+ *
122
+ * This used to be a cast over resolve(), which made it correct at exactly one cardinality:
123
+ * an empty key aborted the boot, and a single implementation was injected as a bare
124
+ * instance whose first `.length` / `for...of` / `.map()` failed at runtime.
125
+ *
126
+ * @param {string} key - Strategy (interface) key
127
+ * @returns {Promise<T[]>} Every implementation, empty when the key has none
128
+ */
129
+ resolveStrategy<T>(key: string): Promise<T[]>;
130
+ /**
131
+ * @typeOfComponent is the type of the component
132
+ *
133
+ * */
134
+ resolveAll<T>(typeOfComponent: ComponentKind): Promise<(T | T[])[]>;
135
+ private filterServices;
136
+ private resolveContainerService;
137
+ private resolveMultipleContainerService;
138
+ /**
139
+ * @description Register a ComponentPostProcessor for post-processing newly created instances.
140
+ * PostProcessors are called in FIFO order after DI + PostConstruct.
141
+ * @param {ComponentPostProcessor} processor - The post-processor to register
142
+ */
143
+ registerPostProcessor(processor: ComponentPostProcessor): void;
144
+ /**
145
+ * @description Choose whether construction runs start hooks or hands them to LifecycleService.
146
+ *
147
+ * The IoC engine switches to `deferred` around user components only. Post-processors keep
148
+ * running theirs at construction because `postProcess()` reads state a start hook sets - defer
149
+ * that and every component the processor wraps is built against an uninitialised processor.
150
+ *
151
+ * @param {StartHookMode} mode - immediate (default) or deferred
152
+ * @returns {void}
153
+ */
154
+ setStartHookMode(mode: StartHookMode): void;
155
+ /**
156
+ * @description Singletons in registration order, for the start/stop lifecycle.
157
+ * @returns {LifecycleComponent[]} The live list - LifecycleService flips `started` on it
158
+ */
159
+ get lifecycle(): LifecycleComponent[];
160
+ private prepareInstance;
161
+ /**
162
+ * @description Run every @OnStart (and its @PostConstruct alias) method on an instance.
163
+ *
164
+ * Walks the prototype chain ancestors-first and runs each method name once, so a hook
165
+ * inherited by three classes still fires once.
166
+ *
167
+ * A failure used to `process.exit(1)` here, which turned one broken component into a suite
168
+ * reporting `0 pass / 1 fail` with no indication of why. It now throws, naming the hook, with
169
+ * the original error as `cause` - the boot fails, the process decides what to do about it.
170
+ *
171
+ * @param {any} instance - The instance to run hooks on
172
+ * @param {Class} Class - The class of the instance
173
+ * @returns {Promise<void>}
174
+ */
175
+ executeStartHooks(instance: any, Class: Class): Promise<void>;
176
+ /**
177
+ * @description The @OnStop method names for a class, in the order they should run.
178
+ *
179
+ * Reversed relative to the start hooks so a component tears down in the opposite order it
180
+ * was brought up, matching how LifecycleService walks the components themselves.
181
+ *
182
+ * @param {Class} Class - The class to inspect
183
+ * @returns {string[]} Method names, empty when the class declares none
184
+ */
185
+ getStopHooks(Class: Class): string[];
186
+ /**
187
+ * @description The @OnStart method names for a class, in the order they run.
188
+ * @param {Class} Class - The class to inspect
189
+ * @returns {string[]} Method names, empty when the class declares none
190
+ */
191
+ getStartHooks(Class: Class): string[];
192
+ /**
193
+ * @description Collect decorated method names across the prototype chain, de-duplicated.
194
+ * @param {Class} Class - The class to inspect
195
+ * @param {symbol} metadataKey - Which hook list to read
196
+ * @returns {string[]} Method names, ancestors first
197
+ */
198
+ private collectHookMethods;
199
+ private injectStrategies;
200
+ /**
201
+ * @description Assigns every @Value field of the instance from process.env.
202
+ *
203
+ * Values land as plain writable properties - unlike @Inject fields they hold no
204
+ * resolved service to protect, and tests overwrite them freely. The own-property
205
+ * guard mirrors injectDependencies: a field initializer wins over the environment.
206
+ *
207
+ * @param {any} newInstance - The freshly constructed instance
208
+ * @param {Class} Class - The class of the instance
209
+ * @returns {void}
210
+ */
211
+ private injectValues;
212
+ private injectDependencies;
213
+ /**
214
+ * The message behind an assignment to a wired field.
215
+ *
216
+ * Injected fields are installed as accessors with no setter, so assigning to one throws the
217
+ * engine's own `TypeError: Attempted to assign to readonly property.` - no field name, no class,
218
+ * no hint at what to do instead. Everybody reaches for `Object.assign(instance, {dep: fake})`
219
+ * once; this turns that minute into a sentence.
220
+ */
221
+ private injectedFieldMessage;
222
+ /**
223
+ * @description Checks if a class is a framework class (CoreService)
224
+ * Framework classes can traverse the prototype chain even if they contain native code patterns
225
+ * @param {any} cls - The class to check
226
+ * @returns {boolean} True if the class is a framework class
227
+ */
228
+ private isFrameworkClass;
229
+ /**
230
+ * Deliberately NOT `getPrototypeChainOf` from utils, even though the two overlap.
231
+ *
232
+ * This walk carries two rules the generic helper does not: it bails out at a class whose
233
+ * source reads `[native code]` (so injection never tries to walk into a built-in or a bound
234
+ * constructor), with an escape hatch for `@CoreService` classes, and it returns leaf-first
235
+ * because every caller here reverses it themselves.
236
+ *
237
+ * The generic helper is the right reader for decorator metadata; this one guards instance
238
+ * construction. Merging them would mean picking one set of stop conditions for both.
239
+ */
240
+ private getPrototypeChain;
241
+ get services(): {
242
+ [p: string]: ContainerService | ContainerService[];
243
+ };
244
+ set services(value: {
245
+ [p: string]: ContainerService | ContainerService[];
246
+ });
247
+ }