@tsed/di 8.9.2 → 8.9.4

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.
@@ -1,7 +1,7 @@
1
1
  import { ControllerProvider } from "../domain/ControllerProvider.js";
2
2
  import type { Provider } from "../domain/Provider.js";
3
3
  type PickedProps = "scope" | "path" | "alias" | "hooks" | "deps" | "imports" | "configuration" | "priority";
4
- export declare const injectable: import("../utils/providerBuilder.js").ProviderBuilderFn<Provider<any>, PickedProps | "type">;
5
- export declare const interceptor: import("../utils/providerBuilder.js").ProviderBuilderFn<Provider<any>, PickedProps | "type">;
6
- export declare const controller: import("../utils/providerBuilder.js").ProviderBuilderFn<ControllerProvider<any>, PickedProps | "children" | "middlewares">;
4
+ export declare const injectable: import("../utils/providerBuilder.js").ProviderBuilderFn<Provider<any>, "type" | PickedProps>;
5
+ export declare const interceptor: import("../utils/providerBuilder.js").ProviderBuilderFn<Provider<any>, "type" | PickedProps>;
6
+ export declare const controller: import("../utils/providerBuilder.js").ProviderBuilderFn<ControllerProvider<any>, "middlewares" | "children" | PickedProps>;
7
7
  export {};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@tsed/di",
3
3
  "description": "DI module for Ts.ED Framework",
4
4
  "type": "module",
5
- "version": "8.9.2",
5
+ "version": "8.9.4",
6
6
  "source": "./src/index.ts",
7
7
  "main": "./lib/esm/index.js",
8
8
  "module": "./lib/esm/index.js",
@@ -30,12 +30,12 @@
30
30
  "uuid": "^10.0.0"
31
31
  },
32
32
  "devDependencies": {
33
- "@tsed/barrels": "8.9.2",
34
- "@tsed/core": "8.9.2",
35
- "@tsed/hooks": "8.9.2",
33
+ "@tsed/barrels": "8.9.4",
34
+ "@tsed/core": "8.9.4",
35
+ "@tsed/hooks": "8.9.4",
36
36
  "@tsed/logger": "^7.0.1",
37
- "@tsed/schema": "8.9.2",
38
- "@tsed/typescript": "8.9.2",
37
+ "@tsed/schema": "8.9.4",
38
+ "@tsed/typescript": "8.9.4",
39
39
  "cross-env": "7.0.3",
40
40
  "eslint": "9.12.0",
41
41
  "typescript": "5.4.5",
@@ -43,10 +43,10 @@
43
43
  "webpack": "^5.75.0"
44
44
  },
45
45
  "peerDependencies": {
46
- "@tsed/core": ">=8.9.2",
47
- "@tsed/hooks": ">=8.9.2",
46
+ "@tsed/core": ">=8.9.4",
47
+ "@tsed/hooks": ">=8.9.4",
48
48
  "@tsed/logger": ">=7.0.1",
49
- "@tsed/schema": ">=8.9.2"
49
+ "@tsed/schema": ">=8.9.4"
50
50
  },
51
51
  "peerDependenciesMeta": {
52
52
  "@tsed/core": {
package/readme.md CHANGED
@@ -27,130 +27,311 @@
27
27
 
28
28
  <hr />
29
29
 
30
- A package of Ts.ED framework. See website: https://tsed.dev/
30
+ A powerful and flexible Dependency Injection (DI) toolkit inspired by Angular, designed for both TypeScript and pure JavaScript applications. Use it standalone or as the foundation of Ts.ED. Supports both decorator-based and functional (decorator-less) APIs for maximum compatibility, even in non-TypeScript or pure JS projects.
31
31
 
32
- # Installation
32
+ ---
33
33
 
34
- You can get the latest release and the type definitions using npm:
34
+ ## Installation
35
+
36
+ Install the latest release and required peer dependencies:
35
37
 
36
38
  ```bash
37
- npm install --save @tsed/di
39
+ npm install --save @tsed/di @tsed/core @tsed/hooks @tsed/logger @tsed/schema
38
40
  ```
39
41
 
40
- > **Important!** TsExpressDecorators requires Node >= 6, Express >= 4, TypeScript >= 2.0 and
41
- > the `experimentalDecorators`, `emitDecoratorMetadata`, `types` and `lib` compilation
42
- > options in your `tsconfig.json` file.
43
-
44
- ```json
45
- {
46
- "compilerOptions": {
47
- "target": "es2016",
48
- "lib": ["es2016"],
49
- "typeRoots": ["./node_modules/@types"],
50
- "module": "commonjs",
51
- "moduleResolution": "node",
52
- "experimentalDecorators": true,
53
- "emitDecoratorMetadata": true,
54
- "allowSyntheticDefaultImports": true
55
- },
56
- "exclude": ["node_modules"]
57
- }
58
- ```
42
+ > **Important!**
43
+ >
44
+ > - @tsed/di v8+ supports **only ESM** (ECMAScript Modules).
45
+ > - Requires Node >= 20,
46
+ > - TypeScript >= 5.0 if you use decorators.
47
+ > - For TypeScript, enable `emitDecoratorMetadata` and `experimentalDecorators` in your `tsconfig.json`.
59
48
 
60
- ## Introduction
49
+ ---
61
50
 
62
- Basically, almost everything may be considered as a provider – service, factory, intereceptors, and so on.
63
- All of them can inject dependencies, meaning, they can create various relationships with each other.
64
- But in fact, a provider is nothing else than just a simple class annotated with an `@Injectable()` decorator.
51
+ ## Features
65
52
 
66
- ## Usage
53
+ - **[Providers](https://tsed.dev/docs/providers.html):** Register and manage services, factories, values, interceptors, and more.
54
+ - **[Functional API](https://tsed.dev/docs/providers.html#injectable):** Register providers and factories without decorators (for pure JS or decorator-less code).
55
+ - **[Async Factories](https://tsed.dev/docs/custom-providers.html#register-async-factory):** Create providers that resolve asynchronously (e.g., database connections).
56
+ - **[Constants Injection](https://tsed.dev/docs/providers.html#constant):** Use `@Constant()` or `constant()` to inject configuration or static values.
57
+ - **[Value Injection](https://tsed.dev/docs/providers.html#value-refvalue):** Use `@Value()` or `refValue()` to inject resolved provider values.
58
+ - **[InjectContext](https://tsed.dev/docs/providers.html#inject-context):** Access the injection context and advanced DI features.
59
+ - **[Config Sources](https://tsed.dev/docs/configuration/configuration-sources.html):** Load and merge configuration from multiple sources (files, env, remote, etc.).
60
+ - **[Lifecycle hooks](https://tsed.dev/docs/hooks.html):** Manage provider lifecycle with hooks like `$onInit`, `$onDestroy`.
61
+ - **[Lazy loading](https://tsed.dev/docs/providers.html#lazy-load-provider):** Lazily load Node.js ESM modules. The lazy loading feature allows you to declare a provider that is only instantiated when it is first injected. The DI system will dynamically import the ESM module, discover injectable services within it, and instantiate them on demand—enabling efficient code splitting and reducing startup time.
62
+ - **Full TypeScript support:** Type inference with `inject()` and advanced tooling for type-safe DI.
67
63
 
68
- Here is a basic usage to declare an injectable service to another one:
64
+ ---
65
+
66
+ ## Basic Usage (Decorator API)
67
+
68
+ Declare injectable services:
69
69
 
70
70
  ```typescript
71
71
  import {Injectable} from "@tsed/di";
72
- import {Calendar} from "./models/calendar.js";
73
72
 
74
73
  @Injectable()
75
- export class CalendarsService {
76
- private readonly calendars: Calendar[] = [];
77
-
78
- create(calendar: Calendar) {
79
- this.calendars.push(calendar);
74
+ export class UserRepository {
75
+ getUsers() {
76
+ return [{id: 1, name: "Alice"}];
80
77
  }
78
+ }
79
+
80
+ @Injectable()
81
+ export class UserService {
82
+ constructor(private repo: UserRepository) {}
81
83
 
82
- findAll(): Calendar[] {
83
- return this.calendars;
84
+ listUsers() {
85
+ return this.repo.getUsers();
84
86
  }
85
87
  }
86
88
  ```
87
89
 
88
- Here's a CalendarsService, a basic class with one property and two methods. The only new trait is that it uses the `@Injectable()` decorator.
89
- The `@Injectable()` attaches the metadata, thereby Ts.ED knows that this class is a provider.
90
+ Use the dependency injector:
90
91
 
91
- Now we have the service class already done, let's use it inside a controller:
92
+ ```typescript
93
+ import {inject} from "@tsed/di";
94
+ import {UserService} from "./UserService.js";
95
+
96
+ const userService = inject(UserService);
97
+
98
+ console.log(userService.listUsers());
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Usage Outside Ts.ED
104
+
105
+ `@tsed/di` is completely standalone.
106
+ You can use it in any JS/TS project (web, CLI, backend, etc) without Ts.ED.
107
+
108
+ ---
109
+
110
+ ## Stable & Recommended Initialization Example
111
+
112
+ This is the recommended and most stable way to initialize and use the injector, especially when working with advanced scenarios (settings, async providers, custom loggers, etc):
92
113
 
93
114
  ```typescript
94
- import {Controller} from "@tsed/di";
95
- import {Post, Body, Get} from "@tsed/schema";
96
- import {CalendarsService} from "./CalendarsService.js";
97
- import {Calendar} from "./models/Calendar.js";
98
-
99
- @Controller("/calendars")
100
- export class CalendarCtrl {
101
- constructor(private readonly calendarsService: CalendarsService) {}
102
-
103
- @Post()
104
- async create(@Body() calendar: Calendar) {
105
- this.calendarsService.create(calendar);
106
- }
115
+ import {injector, attachLogger, inject} from "@tsed/di";
116
+ import {$log} from "@tsed/logger";
117
+ import {CalendarCtrl} from "./CalendarCtrl.js";
118
+
119
+ // Create a new InjectorService instance
120
+ const inj = injector();
107
121
 
108
- @Get()
109
- async findAll(): Promise<Calendar[]> {
110
- return this.calendarsService.findAll();
122
+ // Register your configuration provider
123
+ inj.addProvider(PlatformConfiguration);
124
+
125
+ // Optionally invoke and set configuration
126
+ inj.settings = inj.invoke(PlatformConfiguration);
127
+ inj.settings.set(settings);
128
+
129
+ // Attach a custom logger (optional)
130
+ attachLogger($log); // Overriding the default logger is not recommended
131
+ // You can use @tsed/logger-connect to bind Ts.ED logger with any other logger
132
+
133
+ // If you have async providers or use the ConfigSource feature, ensure to await load()
134
+ await inj.load();
135
+
136
+ // Retrieve your controller (or any provider)
137
+ const calendarCtrl = inject(CalendarCtrl);
138
+
139
+ // Use your controller/service as needed
140
+ calendarCtrl.create({name: "My calendar"});
141
+ ```
142
+
143
+ ---
144
+
145
+ ## Functional API (Decorator-less / Pure JS, v8+)
146
+
147
+ If you can't or don't want to use decorators (e.g. in pure JavaScript), use the **Functional API** introduced in v8+.
148
+
149
+ For exemple, we can register a provider like this:
150
+
151
+ ```js
152
+ import {injectable, inject} from "@tsed/di";
153
+
154
+ // Define a class as injectable
155
+ export class UserRepository {
156
+ getUsers() {
157
+ return [{id: 1, name: "Alice"}];
111
158
  }
112
159
  }
160
+
161
+ injectable(UserRepository);
113
162
  ```
114
163
 
115
- Finally, we can load the injector and use:
164
+ Then, you can use the `inject()` function to retrieve the instance of the class or any other provider:
116
165
 
117
- ```typescript
118
- import {InjectorService, attachLogger} from "@tsed/di";
166
+ ```js
167
+ import {injectable, inject} from "@tsed/di";
168
+
169
+ // Define a factory function
170
+ export const GET_ALLOWED_USERS = injectable(Symbol.for("GET_ALLOWED_USERS"))
171
+ .factory(() => {
172
+ const userRepository = inject(UserRepository);
173
+ /// do something with userRepository
174
+ const users = userRepository.getAll();
175
+ const allowedRoles = constant("allowedRoles");
176
+
177
+ return userRepository.getUsers().filter((user) => allowedRoles.includes(user.role));
178
+ })
179
+ .token();
180
+ ```
181
+
182
+ After that, we have to initialize the injector and load all providers:
183
+
184
+ ```js
185
+ import {injector, attachLogger, inject} from "@tsed/di";
119
186
  import {$log} from "@tsed/logger";
120
- import {CalendarCtrl} from "./CalendarCtrl.js";
187
+ import "./services/GetAllowerUsers.js"; // just add import is enough to discover the providers
188
+
189
+ // Create a new InjectorService instance
190
+ const inj = injector();
191
+
192
+ // Register your configuration provider
193
+ inj.addProvider(PlatformConfiguration);
121
194
 
122
- async function bootstrap() {
123
- const injector = new InjectorService();
195
+ // Optionally invoke and set configuration
196
+ inj.settings = inj.invoke(PlatformConfiguration);
197
+ inj.settings.set(settings);
124
198
 
125
- // configure the default logger
126
- attachLogger(injector, $log);
199
+ // Attach a custom logger (optional)
200
+ attachLogger($log); // Overriding the default logger is not recommended
201
+ // You can use @tsed/logger-connect to bind Ts.ED logger with any other logger
127
202
 
128
- // Load all providers registered via @Injectable decorator
129
- await injector.load();
203
+ // If you have async providers or use the ConfigSource feature, ensure to await load()
204
+ await inj.load();
205
+ ```
206
+
207
+ The example above is the main point to start the DI system. It should be placed in the main entry file of your application.
208
+
209
+ Now, you can use the `inject()` function to retrieve the instance of the class, injectable provider, or pure JavaScript function.
210
+
211
+ For example, if you want to use the `GET_ALLOWED_USERS` factory in your application, you can do it like this:
212
+
213
+ ```js
214
+ import {injectable, inject} from "@tsed/di";
215
+ import {GET_ALLOWED_USERS} from "./services/GetAllowerUsers.js";
216
+
217
+ // use any framework you want like express.js, hapi.js, etc.
218
+ app.get("/", async (req, res) => {
219
+ const getAllowedUser = inject(GET_ALLOWED_USERS);
220
+ const users = await getAllowedUser();
221
+
222
+ res.json(users);
223
+ });
224
+ ```
225
+
226
+ Here we use the `inject()` function in a pure JavaScript function to retrieve the `GET_ALLOWED_USERS` factory.
227
+ This factory will be executed when the route is called, and it will return the allowed users.
228
+
229
+ In summary:
230
+
231
+ - **No decorators required.**
232
+ - Use `injectable()` to register functions or classes as providers.
233
+ - Use `factory()` or `asyncFactory()` to register (async) factories for advanced usage or for custom tokens.
234
+ - Prefer this approach over `registerProvider` in v8+.
235
+
236
+ ---
130
237
 
131
- const calendarController = injector.get<CalendarCtrl>();
132
- await calendarController.create(new Calendar());
238
+ ## Async Factories
133
239
 
134
- // emit event to trigger actions for third parties modules
135
- await injector.emit("$onReady");
240
+ You can register **async factories** to provide values/services that require asynchronous initialization (e.g., database connections):
241
+
242
+ ```typescript
243
+ import {injectable, inject} from "@tsed/di";
244
+
245
+ const DATABASE = injectable(Symbol.for("DATABASE"))
246
+ .asyncFactory(async () => {
247
+ const db = await connectToDatabase(); // your async init logic
248
+ return db;
249
+ })
250
+ .token();
251
+
252
+ const db = await inject(DATABASE); // Await the async factory
253
+ db.query("SELECT * FROM users");
254
+ ```
255
+
256
+ - Use `.asyncFactory()` for asynchronous initialization.
257
+ - When injecting, **await** the result if the provider is async.
258
+
259
+ ---
260
+
261
+ ## Injecting Constants with `@Constant()` and `@Value()`
262
+
263
+ You can inject constant values or configuration using the `@Constant()` decorator (or `constant()` function in the Functional API):
264
+
265
+ ```typescript
266
+ import {Injectable, Constant} from "@tsed/di";
136
267
 
137
- // And finally destroy injector and his instances (see injector hooks)
138
- await injector.destroy();
268
+ @Injectable()
269
+ export class MyService {
270
+ @Constant("app.token") private token: string;
271
+
272
+ printToken() {
273
+ console.log(this.token); // Value from config
274
+ }
275
+ }
276
+ ```
277
+
278
+ You can also use `@Value()` to inject the resolved value of a provider (by token), or `refValue()` for the functional API:
279
+
280
+ ```typescript
281
+ import {Injectable, Value} from "@tsed/di";
282
+
283
+ @Injectable()
284
+ export class MyService {
285
+ @Value("MY_TOKEN") private value: string;
286
+
287
+ printValue() {
288
+ console.log(this.value); // Value from MY_TOKEN provider
289
+ }
139
290
  }
291
+ ```
292
+
293
+ **Functional API for constants and values:**
140
294
 
141
- bootstrap();
295
+ ```js
296
+ import {constant, refValue, inject} from "@tsed/di";
297
+
298
+ const appToken = constant("app.token", "my-api-token"); // frozen value
299
+ const refAppToken = refValue(); // reference to the app.token value. not frozen
142
300
  ```
143
301
 
144
- ## Custom providers
302
+ - Use `@Constant()`/`constant()` for static configuration values.
303
+ - Use `@Value()`/`refValue()` for dynamic values.
304
+
305
+ Learn more: [Constants and Value Injection](https://tsed.dev/docs/providers.html#constant)
306
+
307
+ ---
308
+
309
+ ## Providers
310
+
311
+ `@tsed/di` supports multiple provider types:
312
+
313
+ - **@Injectable:** Basic class providers.
314
+ - **@Service:** Same as `@Injectable`, for semantic clarity.
315
+ - **@Interceptor:** For registering interceptors.
316
+ - **Functional API:** Use `injectable()`, `.factory()`, `.asyncFactory()`, `.value()` for manual/advanced registration.
317
+ - **Constants:** With `@Constant()`/`constant()`.
318
+ - **Values:** With `@Value()`/`refValue()`.
319
+ - **Scoped providers:** Support for singleton, request, and custom scopes.
320
+
321
+ See [Providers documentation](https://tsed.dev/docs/providers.html).
322
+
323
+ ---
145
324
 
146
- To organize your code Ts.ED DI provide different kind of providers:
325
+ ## Documentation & Resources
147
326
 
148
- - Provider can be declared with `@Injectable`,
149
- - Service can be declared with `@Service`,
150
- - Interceptor can be declared with `@Interceptor`,
151
- - Factory and Value can be declared with `registerProvider` and `registerValue`.
327
+ - **[Providers](https://tsed.dev/docs/providers.html)**
328
+ - **[Custom Providers](https://tsed.dev/docs/custom-providers.html)**
329
+ - **[Constants & Value Injection](https://tsed.dev/docs/providers.html#c)**
330
+ - **[Config Sources](https://tsed.dev/docs/configuration/configuration-sources.html)**
331
+ - **[Functional API](https://tsed.dev/docs/di-functional-api.html)**
332
+ - **[InjectContext](https://tsed.dev/docs/di-injectcontext.html)**
152
333
 
153
- See more details on our documentation https://tsed.dev/providers.html
334
+ ---
154
335
 
155
336
  ## Contributors
156
337