node-dependency-injection 4.0.0-alpha.0 โ†’ 4.0.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 (95) hide show
  1. package/.eslintrc +16 -0
  2. package/.github/workflows/build.yml +24 -0
  3. package/.github/workflows/publish.yml +35 -0
  4. package/.mocharc.yaml +0 -1
  5. package/CHANGELOG-3.md +6 -1
  6. package/CONTRIBUTING.md +2 -2
  7. package/README.md +337 -112
  8. package/UPGRADE-3.0.md +4 -1
  9. package/UPGRADE-4.0.md +50 -0
  10. package/assets/logo.png +0 -0
  11. package/bin/Services/File/XmlAdapter.js +53 -0
  12. package/bin/ndi-container:service.js +5 -0
  13. package/bin/ndi-container:validate.js +116 -0
  14. package/bin/ndi.js +1 -0
  15. package/dist/bin/Services/File/BaseAdapter.js +1 -50
  16. package/dist/bin/Services/File/FileManager.js +1 -55
  17. package/dist/bin/Services/File/JsAdapter.js +1 -62
  18. package/dist/bin/Services/File/JsonAdapter.js +1 -60
  19. package/dist/bin/Services/File/XmlAdapter.js +1 -0
  20. package/dist/bin/Services/File/YamlAdapter.js +1 -67
  21. package/dist/bin/ndi-config:check.js +1 -55
  22. package/dist/bin/ndi-config:create.js +1 -40
  23. package/dist/bin/ndi-container:service.js +1 -131
  24. package/dist/bin/ndi-container:validate.js +2 -0
  25. package/dist/bin/ndi.js +1 -9
  26. package/dist/lib/Autowire.js +1 -281
  27. package/dist/lib/AutowireIdentifier.js +1 -0
  28. package/dist/lib/Compiler.js +1 -101
  29. package/dist/lib/CompilerPass/AutowireOverridePass.js +1 -0
  30. package/dist/lib/CompilerPass/DecoratePass.js +1 -118
  31. package/dist/lib/CompilerPass/OptimizePass.js +1 -60
  32. package/dist/lib/CompilerPass/RemovePass.js +1 -57
  33. package/dist/lib/CompilerPass/index.js +1 -131
  34. package/dist/lib/Condition.js +1 -0
  35. package/dist/lib/ContainerBuilder.js +1 -463
  36. package/dist/lib/ContainerValidator.js +1 -0
  37. package/dist/lib/Definition.js +1 -371
  38. package/dist/lib/Dump/Dumper.js +1 -0
  39. package/dist/lib/Dump/JsDumper.js +1 -0
  40. package/dist/lib/Dump/JsonDumper.js +1 -0
  41. package/dist/lib/Dump/XmlDumper.js +1 -0
  42. package/dist/lib/Dump/YamlDumper.js +1 -0
  43. package/dist/lib/Exception/AbstractServiceException.js +1 -47
  44. package/dist/lib/Exception/AttributesMapException.js +1 -44
  45. package/dist/lib/Exception/CannotAutowireOverrideSearch.js +1 -0
  46. package/dist/lib/Exception/ConfigurationFileNotFoundException.js +1 -47
  47. package/dist/lib/Exception/ContainerDefaultDirMustBeSet.js +1 -0
  48. package/dist/lib/Exception/ContainerValidationError.js +1 -0
  49. package/dist/lib/Exception/DefinitionNotFoundException.js +1 -47
  50. package/dist/lib/Exception/FrozenContainerException.js +1 -44
  51. package/dist/lib/Exception/KeyedGroupNoDefaultException.js +1 -0
  52. package/dist/lib/Exception/KeyedGroupNotFoundException.js +1 -0
  53. package/dist/lib/Exception/KeyedServiceNotFoundException.js +1 -0
  54. package/dist/lib/Exception/LoadMethodNotFoundException.js +1 -47
  55. package/dist/lib/Exception/LoggerWarnMethodNotFoundException.js +1 -44
  56. package/dist/lib/Exception/MethodCallEmptyException.js +1 -44
  57. package/dist/lib/Exception/MethodCallNotFoundException.js +1 -47
  58. package/dist/lib/Exception/NotAbstractServiceException.js +1 -47
  59. package/dist/lib/Exception/PrivateServiceException.js +1 -47
  60. package/dist/lib/Exception/ProcessMethodNotFoundException.js +1 -47
  61. package/dist/lib/Exception/RootDirectoryMustBeAbsolute.js +1 -0
  62. package/dist/lib/Exception/RootDirectoryNotFound.js +1 -0
  63. package/dist/lib/Exception/ServiceCircularReferenceException.js +1 -44
  64. package/dist/lib/Exception/ServiceFileNotAbsolute.js +1 -0
  65. package/dist/lib/Exception/ServiceFileNotFoundException.js +1 -47
  66. package/dist/lib/Exception/ServiceFileNotLoadedException.js +1 -47
  67. package/dist/lib/Exception/ServiceFileNotValidExtension.js +1 -0
  68. package/dist/lib/Exception/ServiceNotFoundException.js +1 -48
  69. package/dist/lib/Exception/UnableToGetInstanceFromId.js +1 -0
  70. package/dist/lib/Exception/WrongCompilerPassTypeException.js +1 -47
  71. package/dist/lib/Exception/WrongDefinitionException.js +1 -44
  72. package/dist/lib/InstanceManager.js +1 -363
  73. package/dist/lib/KeyedGroupReference.js +1 -0
  74. package/dist/lib/KeyedReference.js +1 -0
  75. package/dist/lib/Loader/Argument.js +1 -0
  76. package/dist/lib/Loader/FileLoader.js +1 -417
  77. package/dist/lib/Loader/JsFileLoader.js +1 -68
  78. package/dist/lib/Loader/JsonFileLoader.js +1 -40
  79. package/dist/lib/Loader/XmlFileLoader.js +1 -0
  80. package/dist/lib/Loader/YamlFileLoader.js +1 -88
  81. package/dist/lib/LoggerHelper.js +1 -0
  82. package/dist/lib/PackageReference.js +1 -37
  83. package/dist/lib/ParameterReference.js +1 -0
  84. package/dist/lib/PassConfig.js +1 -78
  85. package/dist/lib/Reference.js +1 -49
  86. package/dist/lib/ServiceFile.js +1 -0
  87. package/dist/lib/TagReference.js +1 -37
  88. package/dist/lib/ValidationResult.js +1 -0
  89. package/dist/lib/index.js +1 -79
  90. package/dist/lib/schema/services.xsd +163 -0
  91. package/dist/lib/types/index.d.ts +173 -11
  92. package/dist/lib/types/tests.ts +36 -2
  93. package/package.json +25 -11
  94. package/tsconfig.json +8 -1
  95. package/.travis.yml +0 -14
package/.eslintrc ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": [
3
+ "plugin:sonarjs/recommended"
4
+ ],
5
+ "plugins": [
6
+ "sonarjs"
7
+ ],
8
+ "parserOptions": {
9
+ "ecmaVersion": "latest",
10
+ "sourceType": "module"
11
+ },
12
+ "rules": {
13
+ "sonarjs/cognitive-complexity": "error",
14
+ "sonarjs/no-identical-expressions": "error"
15
+ }
16
+ }
@@ -0,0 +1,24 @@
1
+ name: Build
2
+
3
+ on:
4
+ push:
5
+ branches: [ master ]
6
+ pull_request:
7
+ branches: [ master ]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ node-version: [ 15.x, 16.x, 17.x, 18.x, 19.x, 20.x, 21.x, 22.x, 23.x, 24.x, 25.x ]
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+ - name: Use Node.js ${{ matrix.node-version }}
18
+ uses: actions/setup-node@v3
19
+ with:
20
+ node-version: ${{ matrix.node-version }}
21
+ - run: npm ci
22
+ - run: npm run build --if-present
23
+ - run: npm run test:standard
24
+ - run: npm test
@@ -0,0 +1,35 @@
1
+ name: Publish
2
+
3
+ on:
4
+ release:
5
+ types: [ created ]
6
+
7
+ permissions:
8
+ contents: read
9
+ id-token: write
10
+
11
+ jobs:
12
+ publish:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: actions/setup-node@v4
18
+ with:
19
+ node-version: 20
20
+ registry-url: https://registry.npmjs.org/
21
+
22
+ # Ensure npm CLI is new enough for Trusted Publishing flows
23
+ - run: npm i -g npm@latest
24
+ - run: npm -v
25
+
26
+ - run: npm ci
27
+
28
+ # Set package.json version from the release tag (e.g. v3.2.7 โ†’ 3.2.7)
29
+ - name: Set version from tag
30
+ run: npm version "${GITHUB_REF_NAME#v}" --no-git-tag-version --ignore-scripts
31
+
32
+ - run: npm run build
33
+
34
+ # Public packages sometimes need this explicitly (safe even if already public)
35
+ - run: npm publish --access public
package/.mocharc.yaml CHANGED
@@ -2,4 +2,3 @@ require: '@babel/register'
2
2
  spec: test/node-dependency-injection/**/*.spec.js
3
3
  color: true
4
4
  ui: bdd
5
- reporter: nyan
package/CHANGELOG-3.md CHANGED
@@ -1,7 +1,12 @@
1
1
  # Change Log
2
2
 
3
- # [3.0.0] - 2022-05-09
3
+ # [3.0.0] - 2022-05-19
4
4
  ### Changed
5
+ - File Loader load method is now Promised
6
+ - ContainerBuilder compile is now Promised
7
+ - ContainerBuilder findDefinition is now Promised
8
+ - Custom Compiler Pass process needs to be Promised
9
+ - Container Builder findTaggedServiceIds returns an Iterable object instead of Map
5
10
  ### Added
6
11
  - Autowire support for TypeScript
7
12
  - Get container service from a class instance
package/CONTRIBUTING.md CHANGED
@@ -52,13 +52,13 @@ $ npm test || test:coverage
52
52
  Please, follow [Standard JS Coding Guidelines](http://standardjs.com)
53
53
 
54
54
  ```console
55
- $ npm run test:standard
55
+ $ npx standard
56
56
  ```
57
57
 
58
58
  and if you want to fix automatically some of your source code
59
59
 
60
60
  ```console
61
- $ npm run test:standard:fix
61
+ $ npx standard --fix
62
62
  ```
63
63
 
64
64
  ### 5. Documentation/Wiki ###
package/README.md CHANGED
@@ -1,81 +1,256 @@
1
- Node Dependency Injection
2
- =========================
1
+ <p align="center">
2
+ <img src="assets/logo.png" alt="Node Dependency Injection" width="480" />
3
+ </p>
3
4
 
4
- ![NDI Logo](http://image.ibb.co/iGnCUn/logojoy.png)
5
+ <h1 align="center">Node Dependency Injection</h1>
5
6
 
6
- #### A special thanks to [Symfony](http://symfony.com) which was a great inspiration and example for this project.
7
+ <p align="center">
8
+ <strong>Standardize and centralize the way objects are constructed in your application.</strong><br/>
9
+ Inspired by the battle-tested <a href="http://symfony.com">Symfony</a> DI container, built for Node.js &amp; TypeScript.
10
+ </p>
7
11
 
8
- The Node Dependency Injection component allows you to standardize and centralize the way objects are constructed in your application.
12
+ <p align="center">
13
+ <a href="https://badge.fury.io/js/node-dependency-injection"><img src="https://badge.fury.io/js/node-dependency-injection.svg" alt="Npm Version" /></a>
14
+ <img src="https://github.com/zazoomauro/node-dependency-injection/actions/workflows/build.yml/badge.svg" alt="Build Status" />
15
+ <a href="https://codecov.io/gh/zazoomauro/node-dependency-injection"><img src="https://codecov.io/gh/zazoomauro/node-dependency-injection/branch/master/graph/badge.svg?token=faEAqrimPR" alt="Code Coverage" /></a>
16
+ <a href="https://www.npmjs.com/package/node-dependency-injection"><img src="https://img.shields.io/npm/dm/node-dependency-injection.svg" alt="Npm Downloads" /></a>
17
+ <a href="https://snyk.io/test/github/zazoomauro/node-dependency-injection"><img src="https://snyk.io/test/github/zazoomauro/node-dependency-injection/badge.svg" alt="Known Vulnerabilities" /></a>
18
+ <a href="https://github.com/zazoomauro/node-dependency-injection/blob/master/LICENCE"><img src="https://img.shields.io/npm/l/node-dependency-injection.svg" alt="License" /></a>
19
+ </p>
9
20
 
10
- [![Npm Version](https://badge.fury.io/js/node-dependency-injection.svg)](https://badge.fury.io/js/node-dependency-injection)
11
- [![Build Status](https://travis-ci.org/zazoomauro/node-dependency-injection.svg?branch=master)](https://travis-ci.org/zazoomauro/node-dependency-injection)
12
- [![Dependencies](https://david-dm.org/zazoomauro/node-dependency-injection.svg)](https://david-dm.org/zazoomauro/node-dependency-injection)
13
- [![DevDependencies](https://david-dm.org/zazoomauro/node-dependency-injection/dev-status.svg)](https://david-dm.org/zazoomauro/node-dependency-injection#info=devDependencies)
14
- [![Code Coverage](https://codecov.io/gh/zazoomauro/node-dependency-injection/branch/master/graph/badge.svg)](https://codecov.io/gh/zazoomauro/node-dependency-injection)
15
- [![Code Climate](https://codeclimate.com/github/zazoomauro/node-dependency-injection/badges/gpa.svg)](https://codeclimate.com/github/zazoomauro/node-dependency-injection)
16
- [![Coding Standard](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
17
- [![Known Vulnerabilities](https://snyk.io/test/github/zazoomauro/node-dependency-injection/badge.svg)](https://snyk.io/test/github/zazoomauro/node-dependency-injection)
18
- [![Npm Downloads](https://img.shields.io/npm/dm/node-dependency-injection.svg?maxAge=2592000)](https://www.npmjs.com/package/node-dependency-injection)
19
- [![License](https://img.shields.io/npm/l/node-dependency-injection.svg?maxAge=2592000?style=plastic)](https://github.com/zazoomauro/node-dependency-injection/blob/master/LICENCE)
21
+ ---
20
22
 
21
- Installation
22
- ------------
23
+ ## Why Node Dependency Injection?
24
+
25
+ Managing dependencies manually leads to tightly coupled, hard-to-test code. **Node Dependency Injection** gives you a powerful, flexible IoC container that wires your application together โ€” keeping your classes clean, your tests simple, and your architecture solid.
26
+
27
+ ---
28
+
29
+ ## โœจ Features
30
+
31
+ | | |
32
+ |---|---|
33
+ | ๐Ÿ”„ **Autowire** โ€” zero-config DI for TypeScript | ๐Ÿ“ **Config files** โ€” YAML, JSON or JS |
34
+ | ๐Ÿญ **Factory pattern** โ€” flexible service creation | ๐Ÿท๏ธ **Service tagging** โ€” group & inject by tag |
35
+ | ๐Ÿ’ค **Lazy services** โ€” instantiate only when needed | ๐ŸŽจ **Decorators** โ€” wrap services transparently |
36
+ | โšก **Compiler passes** โ€” transform the container at build time | ๐Ÿ”’ **Private services** โ€” encapsulate internals |
37
+ | ๐ŸŒณ **Parent / Abstract services** โ€” share config via inheritance | ๐Ÿงฉ **Non-shared services** โ€” new instance per call |
38
+ | ๐ŸŒฟ **Environment parameters** โ€” `%env(VAR)%` support | ๐Ÿ—‘๏ธ **Deprecation warnings** โ€” mark services as deprecated |
39
+ | ๐Ÿ“ฆ **Express middleware** โ€” first-class web framework support | ๐Ÿ–ฅ๏ธ **CLI** โ€” inspect &amp; validate your container |
40
+ | ๐Ÿ”€ **Conditional services** โ€” register services based on env or other services | ๐Ÿ—๏ธ **Keyed services** โ€” named strategy pattern with `registerKeyed` |
41
+ | ๐Ÿ”— **Autowire + Keyed** โ€” inject keyed services via parameter binds | |
42
+
43
+ ---
44
+
45
+ ## ๐Ÿ“Š Feature Comparison (NDI vs InversifyJS vs tsyringe vs Awilix)
46
+
47
+ | Feature | node-dependency-injection | InversifyJS | tsyringe | Awilix |
48
+ |---|---|---|---|---|
49
+ | Config files (YAML / JSON / JS) | โœ… Native | โš ๏ธ Programmatic-first | โš ๏ธ Programmatic-first | โš ๏ธ Programmatic-first |
50
+ | TypeScript autowire without decorators | โœ… Native | โŒ | โŒ | โŒ |
51
+ | Keyed services (named strategy groups) | โœ… Native | โš ๏ธ Via custom patterns | โš ๏ธ Via tokens/patterns | โš ๏ธ Via aliases/patterns |
52
+ | Conditional service registration | โœ… Native | โš ๏ธ Manual logic | โš ๏ธ Manual logic | โš ๏ธ Manual logic |
53
+ | Compiler passes / compile-time transforms | โœ… Native | โŒ | โŒ | โŒ |
54
+ | Service tags and tagged lookup | โœ… Native | โš ๏ธ Manual metadata patterns | โš ๏ธ Manual token patterns | โš ๏ธ Naming/registration patterns |
55
+ | Private services | โœ… Native | โš ๏ธ Container conventions | โš ๏ธ Container conventions | โš ๏ธ Container conventions |
56
+ | CLI container inspection / validation | โœ… Native (`ndi`) | โŒ | โŒ | โŒ |
57
+ | Parent / abstract definitions | โœ… Native | โš ๏ธ Composition-based | โš ๏ธ Composition-based | โš ๏ธ Composition-based |
58
+ | Lazy services | โœ… Native | โœ… | โš ๏ธ Partial patterns | โš ๏ธ Partial patterns |
59
+
60
+ > Legend: โœ… built-in, โš ๏ธ possible with custom conventions or extra setup, โŒ not available as a first-class feature.
61
+
62
+ ---
63
+
64
+ ## ๐Ÿš€ Installation
23
65
 
24
66
  ```sh
25
67
  npm install --save node-dependency-injection
26
68
  ```
27
69
 
28
- Usage: register and get services
29
- -----------
70
+ ---
71
+
72
+ ## ๐Ÿ Quick Start
30
73
 
31
- Imagine you have a `Mailer` class like this:
74
+ Register services and wire them together in seconds:
32
75
 
33
76
  ```js
34
- // services/Mailer.js
77
+ import { ContainerBuilder } from 'node-dependency-injection'
78
+ import Mailer from './services/Mailer'
79
+ import ExampleService from './services/ExampleService'
80
+
81
+ const container = new ContainerBuilder()
82
+
83
+ container.register('service.example', ExampleService)
84
+ container.register('service.mailer', Mailer).addArgument('service.example')
85
+
86
+ await container.compile()
87
+
88
+ const mailer = container.get('service.mailer')
89
+ ```
90
+
91
+ ---
92
+
93
+ ## ๐Ÿ”„ Autowire (TypeScript)
94
+
95
+ Zero-configuration dependency injection โ€” NDI reads your TypeScript type annotations and wires everything automatically:
96
+
97
+ ```ts
98
+ import { ContainerBuilder, Autowire } from 'node-dependency-injection'
35
99
 
36
- export default class Mailer {
37
- /**
38
- * @param {ExampleService} exampleService
39
- */
40
- constructor(exampleService) {
41
- this._exampleService = exampleService;
42
- }
100
+ const container = new ContainerBuilder(false, '/path/to/src')
101
+ const autowire = new Autowire(container)
102
+ await autowire.process()
103
+ await container.compile()
43
104
 
44
- ...
105
+ // Retrieve by class โ€” no string IDs needed
106
+ import SomeService from '@src/service/SomeService'
107
+ const service = container.get(SomeService)
108
+ ```
109
+
110
+ > **Production tip:** dump the autowired config to a YAML file and load it directly in prod โ€” no TypeScript scanning overhead.
111
+
112
+ ```ts
113
+ if (process.env.NODE_ENV === 'development') {
114
+ const autowire = new Autowire(container)
115
+ autowire.serviceFile = new ServiceFile('/dist/services.yaml')
116
+ await autowire.process()
117
+ } else {
118
+ const loader = new YamlFileLoader(container)
119
+ await loader.load('/dist/services.yaml')
45
120
  }
121
+ await container.compile()
46
122
  ```
47
123
 
48
- You can register this in the container as a service:
124
+ The generated `services.yaml` uses **human-readable service IDs** derived from the file path relative to your source root (e.g. `Service/Mailer`), making it easy to review, audit, and debug your application's service graph:
49
125
 
50
- ```js
51
- import {ContainerBuilder} from 'node-dependency-injection'
52
- import Mailer from './services/Mailer'
53
- import ExampleService from './services/ExampleService'
126
+ ```yaml
127
+ # services.yaml (human-readable โ€” default since v4.0)
128
+ services:
129
+ Service/Mailer:
130
+ class: /Service/Mailer
131
+ arguments:
132
+ - '@Service/Transport'
133
+ Service/Transport:
134
+ class: /Service/Transport
135
+ arguments: []
136
+ ```
54
137
 
55
- let container = new ContainerBuilder()
138
+ ### Service ID strategy
56
139
 
57
- container
58
- .register('service.example', ExampleService)
140
+ | Strategy | Default | Service ID example | Description |
141
+ |---|---|---|---|
142
+ | `readable` | โœ… v4.0+ | `Service/Mailer` | Path relative to `defaultDir`, extension stripped |
143
+ | `legacy` | v3.x | `U2VydmljZS9NYWlsZXI=` | Base64-encoded absolute path |
59
144
 
60
- container
61
- .register('service.mailer', Mailer)
62
- .addArgument('service.example')
145
+ To opt back in to the legacy strategy (e.g. for gradual migration):
146
+
147
+ ```ts
148
+ const autowire = new Autowire(container)
149
+ autowire.makeIdLegacy() // switch back to base64-encoded IDs
63
150
  ```
64
151
 
65
- And get services from your container
152
+ ---
153
+
154
+ ## ๐Ÿ—๏ธ Keyed Services
155
+
156
+ Keyed services let you register multiple implementations of the same interface under a named group, then retrieve a specific one by key or inject the entire group as a `Map`.
157
+
158
+ ### Programmatic API
66
159
 
67
160
  ```js
68
- const mailer = container.get('service.mailer')
161
+ import { ContainerBuilder, KeyedReference, KeyedGroupReference } from 'node-dependency-injection'
162
+ import StripePayment from './payments/StripePayment'
163
+ import PaypalPayment from './payments/PaypalPayment'
164
+ import CheckoutService from './CheckoutService'
165
+ import PaymentRouter from './PaymentRouter'
166
+
167
+ const container = new ContainerBuilder()
168
+
169
+ // Register implementations under the 'payment' group
170
+ container.registerKeyed('payment', 'stripe', StripePayment).setDefault(true)
171
+ container.registerKeyed('payment', 'paypal', PaypalPayment)
172
+
173
+ // Inject a specific key
174
+ container.register('checkout', CheckoutService)
175
+ .addArgument(new KeyedReference('payment', 'stripe'))
176
+
177
+ // Inject the full group as a Map<key, instance>
178
+ container.register('payment.router', PaymentRouter)
179
+ .addArgument(new KeyedGroupReference('payment'))
180
+
181
+ // Retrieve by key or get the default
182
+ const stripe = container.getKeyed('payment', 'stripe')
183
+ const defaultPayment = container.getKeyed('payment') // returns the .setDefault(true) one
184
+ const allPayments = container.getKeyedGroup('payment') // Map { 'stripe' => โ€ฆ, 'paypal' => โ€ฆ }
185
+ ```
186
+
187
+ ### YAML configuration
188
+
189
+ ```yaml
190
+ services:
191
+ payment.stripe:
192
+ class: 'payments/StripePayment'
193
+ keyed:
194
+ group: payment
195
+ key: stripe
196
+ default: true
197
+
198
+ payment.paypal:
199
+ class: 'payments/PaypalPayment'
200
+ keyed:
201
+ group: payment
202
+ key: paypal
203
+
204
+ checkout:
205
+ class: 'CheckoutService'
206
+ arguments: ['@keyed(payment, stripe)']
207
+
208
+ payment.router:
209
+ class: 'PaymentRouter'
210
+ arguments: ['@keyed_group(payment)']
211
+ ```
212
+
213
+ ### Autowire integration
214
+
215
+ When using Autowire you can inject keyed services into **typed** constructor parameters by registering a bind whose name matches the parameter name:
216
+
217
+ ```typescript
218
+ // TypeScript service
219
+ export default class CheckoutService {
220
+ constructor(private readonly payment: IPaymentService) {}
221
+ }
222
+
223
+ export default class PaymentRouter {
224
+ constructor(private readonly payments: Map<string, IPaymentService>) {}
225
+ }
226
+ ```
227
+
228
+ ```js
229
+ container.registerKeyed('payment', 'stripe', StripePaymentService)
230
+ container.registerKeyed('payment', 'paypal', PaypalPaymentService)
231
+
232
+ // The bind name must match the constructor parameter name exactly
233
+ container.addBind('payment', new KeyedReference('payment', 'stripe'))
234
+ container.addBind('payments', new KeyedGroupReference('payment'))
235
+
236
+ const autowire = new Autowire(container)
237
+ await autowire.process()
238
+ await container.compile()
239
+
240
+ // container.get(CheckoutService).payment โ†’ StripePaymentService
241
+ // container.get(PaymentRouter).payments โ†’ Map { 'stripe' => โ€ฆ, 'paypal' => โ€ฆ }
69
242
  ```
70
243
 
244
+ > **Note:** binds take priority over type-based resolution. The same mechanism works for scalar values โ€” `container.addBind('apiKey', '%env(API_KEY)%')` โ€” so keyed service binds fit naturally into the existing bind API.
71
245
 
72
- Configuration files: how to load and use configuration files
73
- ------------
246
+ ---
74
247
 
75
- You can also use configuration files to improve your service configuration
248
+ ## ๐Ÿ“ Configuration Files
249
+
250
+ Prefer declarative config? Use YAML, JSON or JS:
76
251
 
77
252
  ```yaml
78
- # /path/to/file.yml
253
+ # services.yaml
79
254
  services:
80
255
  service.example:
81
256
  class: 'services/ExampleService'
@@ -86,97 +261,147 @@ services:
86
261
  ```
87
262
 
88
263
  ```js
89
- import {ContainerBuilder, YamlFileLoader} from 'node-dependency-injection'
264
+ import { ContainerBuilder, YamlFileLoader } from 'node-dependency-injection'
265
+
266
+ const container = new ContainerBuilder()
267
+ const loader = new YamlFileLoader(container)
268
+ await loader.load('/path/to/services.yaml')
269
+ await container.compile()
90
270
 
91
- let container = new ContainerBuilder()
92
- let loader = new YamlFileLoader(container)
93
- loader.load('/path/to/file.yml')
271
+ const mailer = container.get('service.mailer')
94
272
  ```
95
273
 
96
- And get services from your container easily
274
+ ---
275
+
276
+ ## ๐Ÿ”€ Conditional Services
277
+
278
+ Register services only when specific conditions are met โ€” evaluated at `compile()` time.
97
279
 
98
280
  ```js
99
- ...
100
- const mailer = container.get('service.mailer')
281
+ import { ContainerBuilder, Condition } from 'node-dependency-injection'
282
+
283
+ const container = new ContainerBuilder()
284
+
285
+ // Register only when an environment variable is set
286
+ container.register('cache.redis', RedisCache)
287
+ .setCondition(Condition.envExists('REDIS_URL'))
288
+
289
+ // Fallback: register only when another service was NOT registered (TryAdd)
290
+ container.register('cache.memory', InMemoryCache)
291
+ .whenMissing('cache.redis')
292
+
293
+ // Register only when a sibling service IS registered
294
+ container.register('metrics', Prometheus)
295
+ .whenServiceExists('http.server')
296
+
297
+ // Combine conditions
298
+ container.register('feature.x', FeatureX)
299
+ .setCondition(Condition.all(
300
+ Condition.envEquals('NODE_ENV', 'production'),
301
+ Condition.envExists('FEATURE_X_ENABLED')
302
+ ))
303
+
304
+ await container.compile()
305
+ ```
306
+
307
+ The same conditions are available declaratively in YAML:
308
+
309
+ ```yaml
310
+ services:
311
+ cache.redis:
312
+ class: 'services/cache/RedisCache'
313
+ when:
314
+ env_exists: REDIS_URL
315
+
316
+ cache.memory:
317
+ class: 'services/cache/InMemoryCache'
318
+ when:
319
+ missing: cache.redis
320
+
321
+ metrics.prometheus:
322
+ class: 'services/metrics/Prometheus'
323
+ when:
324
+ service_exists: http.server
325
+
326
+ logger.verbose:
327
+ class: 'services/logger/VerboseLogger'
328
+ when:
329
+ env_equals: { var: LOG_LEVEL, value: debug }
101
330
  ```
102
331
 
103
- List of features
104
- ------------
105
-
106
- - Configuration files with JS, YAML or JSON.
107
- - Multiple configuration files
108
- - Custom relative service directory
109
- - Compiling container
110
- - Custom compiler pass
111
- - Change definition behaviour
112
- - Using a factory to create services
113
- - Nullable Dependencies
114
- - Public or private services
115
- - Service Aliasing
116
- - Service Tagging
117
- - Parameters Injection
118
- - Lazy Services
119
- - Deprecate Services
120
- - Decorate Services
121
- - Synthetic Services
122
- - Non Shared Services
123
- - Parent and Abstract Services
124
- - Custom Logger
125
- - Container as Service
126
-
127
- > Please read [full documentation](https://github.com/zazoomauro/node-dependency-injection/wiki)
128
-
129
- ExpressJS Usage
130
- ----------------
131
-
132
- If you are using expressJS and you like Node Dependency Injection Framework then I strongly recommend
133
- you to use the `node-dependency-injection-express-middleware` package.
134
- That gives you the possibility to retrieve the container from the request.
332
+ > See the [Conditional Services wiki page](https://github.com/zazoomauro/node-dependency-injection/wiki/ConditionalServices) for the full API reference and advanced usage.
333
+
334
+ ---
335
+
336
+ ## ๐Ÿ“ฆ Ecosystem
337
+
338
+ ### Express Middleware
339
+
340
+ Use NDI seamlessly with Express โ€” retrieve the container directly from any request:
135
341
 
136
342
  ```bash
137
343
  npm install --save node-dependency-injection-express-middleware
138
344
  ```
139
345
 
140
- ```javascript
346
+ ```js
141
347
  import NDIMiddleware from 'node-dependency-injection-express-middleware'
142
348
  import express from 'express'
143
349
 
144
350
  const app = express()
145
-
146
- const options = {serviceFilePath: 'some/path/to/config.yml'}
147
- app.use(new NDIMiddleware(options).middleware())
351
+ app.use(new NDIMiddleware({ serviceFilePath: 'services.yaml' }).middleware())
148
352
  ```
149
353
 
150
354
  > [Express Middleware Documentation](https://github.com/zazoomauro/node-dependency-injection-express-middleware)
151
355
 
152
- TypeScript Usage
153
- ----------------
356
+ ### CLI
154
357
 
155
- If you are using typescript and you like Node Dependency Injection Framework then typing are now provided at `node-dependency-injection` so
156
- you do not have to create custom typing anymore.
358
+ Inspect and validate your container from the command line:
157
359
 
158
360
  ```bash
159
- npm install --save node-dependency-injection
160
- ```
361
+ # Validate a config file
362
+ ndi config:check /path/to/services.yaml
161
363
 
162
- ```typescript
163
- import { ContainerBuilder } from 'node-dependency-injection'
164
- import MongoClient from './services/MongoClient'
165
- import { Env } from './EnvType'
166
-
167
- export async function boot(container = new ContainerBuilder(), env: Env) {
168
- container.register('Service.MongoClient', MongoClient).addArgument({
169
- host: env.HOST,
170
- port: env.PORT,
171
- })
172
- }
364
+ # Inspect a specific service
365
+ ndi container:service /path/to/services.yaml service.mailer
173
366
  ```
174
367
 
175
- Resources
176
- ---------
368
+ ---
369
+
370
+ ## ๐Ÿ“– Documentation
371
+
372
+ The full documentation lives in the [**project wiki**](https://github.com/zazoomauro/node-dependency-injection/wiki), including guides on:
373
+
374
+ - [Getting Started](https://github.com/zazoomauro/node-dependency-injection/wiki/GettingStarted)
375
+ - [Autowire](https://github.com/zazoomauro/node-dependency-injection/wiki/Autowire)
376
+ - [Keyed Services](https://github.com/zazoomauro/node-dependency-injection/wiki/KeyedServices)
377
+ - [Configuration Files](https://github.com/zazoomauro/node-dependency-injection/wiki/ConfigurationFiles)
378
+ - [Compiler Passes](https://github.com/zazoomauro/node-dependency-injection/wiki/CompilerPass)
379
+ - [Conditional Services](https://github.com/zazoomauro/node-dependency-injection/wiki/ConditionalServices)
380
+ - [Tagging Services](https://github.com/zazoomauro/node-dependency-injection/wiki/Tagging)
381
+ - [Factory](https://github.com/zazoomauro/node-dependency-injection/wiki/Factory)
382
+ - [Lazy Services](https://github.com/zazoomauro/node-dependency-injection/wiki/LazyService)
383
+ - [Decorators](https://github.com/zazoomauro/node-dependency-injection/wiki/Decorate)
384
+ - [And much more...](https://github.com/zazoomauro/node-dependency-injection/wiki)
385
+
386
+ ---
387
+
388
+ ## ๐Ÿค Contributing
177
389
 
178
- - [Documentation](https://github.com/zazoomauro/node-dependency-injection/wiki)
179
- - [Collaboration and pull requests](CONTRIBUTING.md)
180
- - [Milestones](https://github.com/zazoomauro/node-dependency-injection/milestones)
181
- - [Twitter @zazoomauro](https://twitter.com/zazoomauro)
390
+ Contributions are welcome! Please read the [contribution guide](CONTRIBUTING.md) before submitting a pull request.
391
+
392
+ - [Open an issue](https://github.com/zazoomauro/node-dependency-injection/issues)
393
+ - [View milestones](https://github.com/zazoomauro/node-dependency-injection/milestones)
182
394
  - [Changelog](CHANGELOG.md)
395
+
396
+ ---
397
+
398
+ ## ๐Ÿ™ Credits
399
+
400
+ Inspired by the [Symfony](http://symfony.com) Dependency Injection component โ€” a special thanks to the Symfony team for their outstanding work.
401
+
402
+ ---
403
+
404
+ <p align="center">
405
+ <a href="https://github.com/zazoomauro/node-dependency-injection/blob/master/LICENCE">MIT License</a> &nbsp;ยท&nbsp;
406
+ Made with โค๏ธ by <a href="https://twitter.com/zazoomauro">@zazoomauro</a>
407
+ </p>
package/UPGRADE-3.0.md CHANGED
@@ -3,4 +3,7 @@ UPGRADE FROM 2.x to 3.x
3
3
 
4
4
  ### Removed deprecations
5
5
 
6
- - Nothing
6
+ - FileLoader load method is now Promised. Add await to be sync
7
+ - ContainerBuilder compile method is now Promised. Add await to be sync
8
+ - All your custom Compiler Pass process method needs to be promised
9
+ - Container Builder findTaggedServiceIds returns an Iterable object instead of Map