@decaf-ts/injectable-decorators 1.6.1 → 1.6.2

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.
package/LICENSE.md CHANGED
@@ -1,157 +1,21 @@
1
- # GNU LESSER GENERAL PUBLIC LICENSE
2
-
3
- Version 3, 29 June 2007
4
-
5
- Copyright (C) 2025 Tiago Venceslau
6
- <https:/github.com/TiagoVenceslau>
7
-
8
- Everyone is permitted to copy and distribute verbatim copies of this
9
- license document, but changing it is not allowed.
10
-
11
- This version of the GNU Lesser General Public License incorporates the
12
- terms and conditions of version 3 of the GNU General Public License,
13
- supplemented by the additional permissions listed below.
14
-
15
- ## 0. Additional Definitions.
16
-
17
- As used herein, "this License" refers to version 3 of the GNU Lesser
18
- General Public License, and the "GNU GPL" refers to version 3 of the
19
- GNU General Public License.
20
-
21
- "The Library" refers to a covered work governed by this License, other
22
- than an Application or a Combined Work as defined below.
23
-
24
- An "Application" is any work that makes use of an interface provided
25
- by the Library, but which is not otherwise based on the Library.
26
- Defining a subclass of a class defined by the Library is deemed a mode
27
- of using an interface provided by the Library.
28
-
29
- A "Combined Work" is a work produced by combining or linking an
30
- Application with the Library. The particular version of the Library
31
- with which the Combined Work was made is also called the "Linked
32
- Version".
33
-
34
- The "Minimal Corresponding Source" for a Combined Work means the
35
- Corresponding Source for the Combined Work, excluding any source code
36
- for portions of the Combined Work that, considered in isolation, are
37
- based on the Application, and not on the Linked Version.
38
-
39
- The "Corresponding Application Code" for a Combined Work means the
40
- object code and/or source code for the Application, including any data
41
- and utility programs needed for reproducing the Combined Work from the
42
- Application, but excluding the System Libraries of the Combined Work.
43
-
44
- ## 1. Exception to Section 3 of the GNU GPL.
45
-
46
- You may convey a covered work under sections 3 and 4 of this License
47
- without being bound by section 3 of the GNU GPL.
48
-
49
- ## 2. Conveying Modified Versions.
50
-
51
- If you modify a copy of the Library, and, in your modifications, a
52
- facility refers to a function or data to be supplied by an Application
53
- that uses the facility (other than as an argument passed when the
54
- facility is invoked), then you may convey a copy of the modified
55
- version:
56
-
57
- - a) under this License, provided that you make a good faith effort
58
- to ensure that, in the event an Application does not supply the
59
- function or data, the facility still operates, and performs
60
- whatever part of its purpose remains meaningful, or
61
- - b) under the GNU GPL, with none of the additional permissions of
62
- this License applicable to that copy.
63
-
64
- ## 3. Object Code Incorporating Material from Library Header Files.
65
-
66
- The object code form of an Application may incorporate material from a
67
- header file that is part of the Library. You may convey such object
68
- code under terms of your choice, provided that, if the incorporated
69
- material is not limited to numerical parameters, data structure
70
- layouts and accessors, or small macros, inline functions and templates
71
- (ten or fewer lines in length), you do both of the following:
72
-
73
- - a) Give prominent notice with each copy of the object code that
74
- the Library is used in it and that the Library and its use are
75
- covered by this License.
76
- - b) Accompany the object code with a copy of the GNU GPL and this
77
- license document.
78
-
79
- ## 4. Combined Works.
80
-
81
- You may convey a Combined Work under terms of your choice that, taken
82
- together, effectively do not restrict modification of the portions of
83
- the Library contained in the Combined Work and reverse engineering for
84
- debugging such modifications, if you also do each of the following:
85
-
86
- - a) Give prominent notice with each copy of the Combined Work that
87
- the Library is used in it and that the Library and its use are
88
- covered by this License.
89
- - b) Accompany the Combined Work with a copy of the GNU GPL and this
90
- license document.
91
- - c) For a Combined Work that displays copyright notices during
92
- execution, include the copyright notice for the Library among
93
- these notices, as well as a reference directing the user to the
94
- copies of the GNU GPL and this license document.
95
- - d) Do one of the following:
96
- - 0) Convey the Minimal Corresponding Source under the terms of
97
- this License, and the Corresponding Application Code in a form
98
- suitable for, and under terms that permit, the user to
99
- recombine or relink the Application with a modified version of
100
- the Linked Version to produce a modified Combined Work, in the
101
- manner specified by section 6 of the GNU GPL for conveying
102
- Corresponding Source.
103
- - 1) Use a suitable shared library mechanism for linking with
104
- the Library. A suitable mechanism is one that (a) uses at run
105
- time a copy of the Library already present on the user's
106
- computer system, and (b) will operate properly with a modified
107
- version of the Library that is interface-compatible with the
108
- Linked Version.
109
- - e) Provide Installation Information, but only if you would
110
- otherwise be required to provide such information under section 6
111
- of the GNU GPL, and only to the extent that such information is
112
- necessary to install and execute a modified version of the
113
- Combined Work produced by recombining or relinking the Application
114
- with a modified version of the Linked Version. (If you use option
115
- 4d0, the Installation Information must accompany the Minimal
116
- Corresponding Source and Corresponding Application Code. If you
117
- use option 4d1, you must provide the Installation Information in
118
- the manner specified by section 6 of the GNU GPL for conveying
119
- Corresponding Source.)
120
-
121
- ## 5. Combined Libraries.
122
-
123
- You may place library facilities that are a work based on the Library
124
- side by side in a single library together with other library
125
- facilities that are not Applications and are not covered by this
126
- License, and convey such a combined library under terms of your
127
- choice, if you do both of the following:
128
-
129
- - a) Accompany the combined library with a copy of the same work
130
- based on the Library, uncombined with any other library
131
- facilities, conveyed under the terms of this License.
132
- - b) Give prominent notice with the combined library that part of it
133
- is a work based on the Library, and explaining where to find the
134
- accompanying uncombined form of the same work.
135
-
136
- ## 6. Revised Versions of the GNU Lesser General Public License.
137
-
138
- The Free Software Foundation may publish revised and/or new versions
139
- of the GNU Lesser General Public License from time to time. Such new
140
- versions will be similar in spirit to the present version, but may
141
- differ in detail to address new problems or concerns.
142
-
143
- Each version is given a distinguishing version number. If the Library
144
- as you received it specifies that a certain numbered version of the
145
- GNU Lesser General Public License "or any later version" applies to
146
- it, you have the option of following the terms and conditions either
147
- of that published version or of any later version published by the
148
- Free Software Foundation. If the Library as you received it does not
149
- specify a version number of the GNU Lesser General Public License, you
150
- may choose any version of the GNU Lesser General Public License ever
151
- published by the Free Software Foundation.
152
-
153
- If the Library as you received it specifies that a proxy can decide
154
- whether future versions of the GNU Lesser General Public License shall
155
- apply, that proxy's public statement of acceptance of any version is
156
- permanent authorization for you to choose that version for the
157
- Library.
1
+ # MIT License
2
+
3
+ Copyright (c) 2025 Tiago Venceslau
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,7 +1,8 @@
1
1
  ![Banner](./workdocs/assets/Banner.png)
2
2
  ## Simple Injectables engine
3
3
 
4
- Simple implementation of injectables
4
+ A lightweight TypeScript dependency injection library that provides decorators for marking classes as injectable singletons and injecting dependencies into class properties. It features a centralized registry for managing dependencies, lazy loading of injected properties, and support for custom transformations of injected instances.
5
+
5
6
 
6
7
  ![Licence](https://img.shields.io/github/license/decaf-ts/injectable-decorators.svg?style=plastic)
7
8
  ![GitHub language count](https://img.shields.io/github/languages/count/decaf-ts/injectable-decorators?style=plastic)
@@ -34,17 +35,283 @@ Documentation available [here](https://decaf-ts.github.io/injectable-decorators/
34
35
 
35
36
  ### Description
36
37
 
37
- Standalone module, exposes a simple implementation for Dependency injection:
38
- - Injectables are singletons;
39
- - they are injected by overriding a class's attribute `getter` and are only requested when actually needed, simplifying the injection order;
40
- - Developer is responsible for originally instantiating them;
38
+ The `injectable-decorators` library is a standalone module that provides a lightweight and flexible dependency injection system for TypeScript applications. It is designed to simplify the management of dependencies between components in your application through the use of TypeScript decorators.
39
+
40
+ #### Core Components
41
+
42
+ 1. **Injectables Registry**
43
+ - The central component that manages all injectable objects
44
+ - Maintains a cache of singleton instances
45
+ - Provides methods for registering, retrieving, and building injectable objects
46
+ - Can be customized with a different implementation if needed
47
+
48
+ 2. **Decorators**
49
+ - `@injectable()`: Class decorator that marks a class as available for dependency injection
50
+ - Transforms the class into a singleton that can be retrieved from the registry
51
+ - Supports optional category naming for minification safety
52
+ - Allows for custom callbacks after instance creation
53
+ - `@inject()`: Property decorator that injects a dependency into a class property
54
+ - Automatically resolves the dependency type from TypeScript's type system
55
+ - Supports custom transformers to modify the injected instance
56
+ - Implements lazy loading - dependencies are only instantiated when accessed
57
+
58
+ 3. **Reflection Utilities**
59
+ - Uses TypeScript's reflection metadata to determine property types
60
+ - Provides utilities for working with type information in decorators
61
+
62
+ #### Key Features
63
+
64
+ - **Singleton Management**: Injectables are typically managed as singletons, ensuring consistent state across your application.
65
+ - **Lazy Loading**: Dependencies are only instantiated when they are actually accessed, simplifying the injection order and improving performance.
66
+ - **Type Safety**: Leverages TypeScript's type system to ensure type safety in injected dependencies.
67
+ - **Minification Support**: Provides options to specify explicit names for injectables to handle minification scenarios.
68
+ - **Custom Transformations**: Supports transforming injectable instances before they're injected into target objects.
69
+ - **Selective Reset**: Ability to selectively reset specific injectables in the registry based on name patterns.
70
+
71
+ #### Design Philosophy
72
+
73
+ The library follows a minimalist approach, focusing on providing essential dependency injection capabilities without unnecessary complexity. It's designed to be:
74
+
75
+ - **Lightweight**: Small footprint with minimal dependencies
76
+ - **Flexible**: Adaptable to different application architectures
77
+ - **Intuitive**: Simple API that follows natural TypeScript patterns
78
+ - **Non-intrusive**: Minimal impact on your existing code structure
79
+
80
+ Unlike more complex DI frameworks, this library doesn't require extensive configuration or setup. The developer is responsible for initially decorating classes and properties, but the library handles the instantiation and injection process automatically.
81
+
41
82
 
42
83
  ### How to Use
43
84
 
44
85
  - [Initial Setup](./tutorials/For%20Developers.md#_initial-setup_)
45
86
  - [Installation](./tutorials/For%20Developers.md#installation)
46
87
 
88
+ ## Basic Usage Examples
89
+
90
+ ### Creating an Injectable Service
91
+
92
+ **Use Case**: You want to create a service that can be injected into other components of your application.
93
+
94
+ ```typescript
95
+ import { injectable } from 'injectable-decorators';
96
+
97
+ @injectable()
98
+ class LoggerService {
99
+ log(message: string): void {
100
+ console.log(`[LOG]: ${message}`);
101
+ }
102
+
103
+ error(message: string): void {
104
+ console.error(`[ERROR]: ${message}`);
105
+ }
106
+ }
107
+
108
+ // The service is automatically registered in the Injectables registry
109
+ // and will be available for injection
110
+ ```
111
+
112
+ ### Injecting a Service into a Component
113
+
114
+ **Use Case**: You want to use a service in a component without manually creating an instance.
115
+
116
+ ```typescript
117
+ import { inject } from 'injectable-decorators';
118
+ import { LoggerService } from './logger.service';
119
+
120
+ class UserComponent {
121
+ @inject()
122
+ private logger!: LoggerService;
123
+
124
+ createUser(username: string): void {
125
+ this.logger.log(`Creating user: ${username}`);
126
+ // User creation logic...
127
+ this.logger.log(`User ${username} created successfully`);
128
+ }
129
+ }
130
+
131
+ // When the logger property is accessed, the LoggerService instance
132
+ // will be automatically injected
133
+ ```
134
+
135
+ ### Using a Custom Category Name
136
+
137
+ **Use Case**: You want to ensure your injectables work correctly even after code minification, or you want to use a different name for the injectable.
138
+
139
+ ```typescript
140
+ import { injectable } from 'injectable-decorators';
141
+
142
+ @injectable('AuthService')
143
+ class AuthenticationService {
144
+ authenticate(username: string, password: string): boolean {
145
+ // Authentication logic...
146
+ return true;
147
+ }
148
+ }
149
+
150
+ class LoginComponent {
151
+ @inject('AuthService')
152
+ private auth!: AuthenticationService;
153
+
154
+ login(username: string, password: string): void {
155
+ if (this.auth.authenticate(username, password)) {
156
+ console.log('Login successful');
157
+ } else {
158
+ console.log('Login failed');
159
+ }
160
+ }
161
+ }
162
+ ```
163
+
164
+ ### Using a Transformer with Inject
165
+
166
+ **Use Case**: You want to transform or configure an injectable instance before it's used.
167
+
168
+ ```typescript
169
+ import { inject, InstanceTransformer } from 'injectable-decorators';
170
+
171
+ @injectable()
172
+ class ConfigService {
173
+ private config: Record<string, any> = {
174
+ apiUrl: 'https://api.example.com',
175
+ timeout: 5000
176
+ };
177
+
178
+ get(key: string): any {
179
+ return this.config[key];
180
+ }
181
+ }
182
+
183
+ // Transformer function that adds environment-specific configuration
184
+ const configTransformer: InstanceTransformer = (config: ConfigService, target: any) => {
185
+ // You could customize the config based on the target or environment
186
+ return config;
187
+ };
188
+
189
+ class ApiClient {
190
+ @inject(undefined, configTransformer)
191
+ private config!: ConfigService;
192
+
193
+ fetchData(): Promise<any> {
194
+ const apiUrl = this.config.get('apiUrl');
195
+ const timeout = this.config.get('timeout');
196
+
197
+ // Use the configured values...
198
+ return Promise.resolve({ data: 'example' });
199
+ }
200
+ }
201
+ ```
202
+
203
+ ### Manually Registering and Retrieving Injectables
204
+
205
+ **Use Case**: You want to manually register an existing instance or retrieve an injectable instance directly.
206
+
207
+ ```typescript
208
+ import { Injectables } from 'injectable-decorators';
209
+
210
+ // Register an existing instance
211
+ const databaseConnection = {
212
+ query: (sql: string) => Promise.resolve([]),
213
+ close: () => Promise.resolve()
214
+ };
215
+
216
+ Injectables.register(databaseConnection, 'DatabaseConnection');
217
+
218
+ // Retrieve the instance elsewhere in your code
219
+ class QueryService {
220
+ private db = Injectables.get<typeof databaseConnection>('DatabaseConnection');
221
+
222
+ async executeQuery(sql: string): Promise<any[]> {
223
+ if (!this.db) {
224
+ throw new Error('Database connection not available');
225
+ }
226
+ return this.db.query(sql);
227
+ }
228
+ }
229
+ ```
230
+
231
+ ### Creating a Custom Injectable Registry
232
+
233
+ **Use Case**: You want to customize how injectables are stored and retrieved, perhaps for testing or to add additional functionality.
234
+
235
+ ```typescript
236
+ import { Injectables, InjectablesRegistry } from 'injectable-decorators';
237
+
238
+ // Create a custom registry implementation
239
+ class LoggingRegistry implements InjectablesRegistry {
240
+ private defaultRegistry: InjectablesRegistry;
241
+
242
+ constructor(defaultRegistry: InjectablesRegistry) {
243
+ this.defaultRegistry = defaultRegistry;
244
+ }
245
+
246
+ get<T>(name: string, ...args: any[]): T | undefined {
247
+ console.log(`Getting injectable: ${name}`);
248
+ return this.defaultRegistry.get<T>(name, ...args);
249
+ }
250
+
251
+ register<T>(constructor: any, ...args: any[]): void {
252
+ console.log(`Registering injectable: ${args[0] || constructor.name}`);
253
+ return this.defaultRegistry.register(constructor, ...args);
254
+ }
255
+
256
+ build<T>(obj: Record<string, any>, ...args: any[]): T {
257
+ console.log(`Building injectable: ${obj.name}`);
258
+ return this.defaultRegistry.build<T>(obj, ...args);
259
+ }
260
+ }
261
+
262
+ // Use the custom registry
263
+ import { InjectableRegistryImp } from 'injectable-decorators';
264
+ const customRegistry = new LoggingRegistry(new InjectableRegistryImp());
265
+ Injectables.setRegistry(customRegistry);
266
+ ```
267
+
268
+ ### Resetting the Registry
269
+
270
+ **Use Case**: You want to clear all registered injectables, perhaps for testing or when switching application contexts.
271
+
272
+ ```typescript
273
+ import { Injectables } from 'injectable-decorators';
274
+
275
+ // Reset all injectables
276
+ Injectables.reset();
277
+
278
+ // Selectively reset injectables matching a pattern
279
+ Injectables.selectiveReset(/^Auth/); // Resets all injectables whose names start with "Auth"
280
+ ```
281
+
282
+ ### Using Callback with Injectable
283
+
284
+ **Use Case**: You want to perform additional setup on an injectable instance after it's created.
285
+
286
+ ```typescript
287
+ import { injectable } from 'injectable-decorators';
288
+
289
+ const setupLogger = (instance: LoggerService) => {
290
+ // Configure the logger after instantiation
291
+ instance.setLogLevel('debug');
292
+ instance.enableConsoleOutput(true);
293
+ };
294
+
295
+ @injectable(undefined, false, setupLogger)
296
+ class LoggerService {
297
+ private logLevel: string = 'info';
298
+ private consoleOutput: boolean = false;
299
+
300
+ setLogLevel(level: string): void {
301
+ this.logLevel = level;
302
+ }
47
303
 
304
+ enableConsoleOutput(enabled: boolean): void {
305
+ this.consoleOutput = enabled;
306
+ }
307
+
308
+ log(message: string): void {
309
+ if (this.consoleOutput) {
310
+ console.log(`[${this.logLevel.toUpperCase()}]: ${message}`);
311
+ }
312
+ }
313
+ }
314
+ ```
48
315
 
49
316
 
50
317
  ### Related