@ooneex/container 0.0.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ooneex
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 ADDED
@@ -0,0 +1,543 @@
1
+ # @ooneex/container
2
+
3
+ A powerful and lightweight Dependency Injection (DI) container for TypeScript/JavaScript applications. Built on top of Inversify, this package provides a simple yet comprehensive API for managing service dependencies and constants with different scoping strategies.
4
+
5
+ ![Browser](https://img.shields.io/badge/Browser-Compatible-green?style=flat-square&logo=googlechrome)
6
+ ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
7
+ ![Deno](https://img.shields.io/badge/Deno-Compatible-blue?style=flat-square&logo=deno)
8
+ ![Node.js](https://img.shields.io/badge/Node.js-Compatible-green?style=flat-square&logo=node.js)
9
+ ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)
10
+ ![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)
11
+
12
+ ## Features
13
+
14
+ ✅ **Service Registration** - Register classes and resolve dependencies automatically
15
+
16
+
17
+ ✅ **Multiple Scopes** - Singleton, Transient, and Request scoping support
18
+
19
+ ✅ **Constant Management** - Store and retrieve constants with string or symbol identifiers
20
+
21
+ ✅ **Type-Safe** - Full TypeScript support with proper type definitions
22
+
23
+ ✅ **Lightweight** - Minimal overhead with powerful dependency injection
24
+
25
+ ✅ **Cross-Platform** - Works in Browser, Node.js, Bun, and Deno
26
+
27
+ ✅ **Error Handling** - Comprehensive error reporting
28
+ with ContainerException
29
+
30
+ ✅ **Service Lifecycle** - Complete control over service creation and removal
31
+
32
+ ✅ **Symbol Support** - Use symbols as identifiers for constants and services
33
+
34
+ ## Installation
35
+
36
+ ### Bun
37
+ ```bash
38
+ bun add @ooneex/container
39
+ ```
40
+
41
+ ### pnpm
42
+ ```bash
43
+ pnpm add @ooneex/container
44
+ ```
45
+
46
+ ### Yarn
47
+ ```bash
48
+ yarn add @ooneex/container
49
+ ```
50
+
51
+ ### npm
52
+ ```bash
53
+ npm install @ooneex/container
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ### Basic Service Registration
59
+
60
+ ```typescript
61
+ import { Container, EContainerScope } from '@ooneex/container';
62
+
63
+ const container = new Container();
64
+
65
+ class DatabaseService {
66
+ public connect(): string {
67
+ return "Connected to database";
68
+ }
69
+ }
70
+
71
+ class UserService {
72
+ private database: DatabaseService;
73
+
74
+ constructor() {
75
+ this.database = container.get(DatabaseService);
76
+ }
77
+
78
+ public createUser(name: string): string {
79
+ this.database.connect();
80
+ return `User ${name} created`;
81
+ }
82
+ }
83
+
84
+ // Register services
85
+ container.add(DatabaseService);
86
+ container.add(UserService);
87
+
88
+ // Resolve an
89
+ d use services
90
+ const userService = container.get(UserService);
91
+ console.log(userService.createUser("John")); // "User John created"
92
+ ```
93
+
94
+ ### Scoping Strategies
95
+
96
+ ```typescript
97
+ import { Container, EContainerScope } from '@ooneex/container';
98
+
99
+ const container = new Container();
100
+
101
+ class SingletonService {
102
+ private static instanceCount = 0;
103
+ public readonly instanceId: number;
104
+
105
+ constructor() {
106
+ this.instanceId = ++SingletonService.instanceCount;
107
+ }
108
+ }
109
+
110
+ class TransientService {
111
+ private static instanceCount = 0;
112
+ public readonly instanceId: number;
113
+
114
+ constructor() {
115
+ this.instanceId = ++TransientService.instanceCount;
116
+ }
117
+ }
118
+
119
+ // Singleton scope (default) - same instance every time
120
+ container.add(SingletonService, EContainerScope.Singleton);
121
+ const singleton1 = container.get(SingletonService);
122
+ const singleton2 = container.get(SingletonService);
123
+ console.log(singleton1.instanceId === singleton2.instanceId); // true
124
+
125
+ // Transient scope - new instance every time
126
+ container.add(TransientService, EContainerScope.Transient);
127
+ const transient1 = container.get(TransientService);
128
+ const transient2 = container.get(TransientService);
129
+ console.log(transient1.instanceId !== transient2.instanceId); // true
130
+ ```
131
+
132
+ ### Constants Management
133
+
134
+ ```typescript
135
+ import { Container } from '@ooneex/container';
136
+
137
+ const container = new Container();
138
+
139
+ // String-based constants
140
+ container.addConstant("API_URL", "https://api.example.com");
141
+ container.addConstant("MAX_RETRIES", 3);
142
+
143
+ // Symbol-based constants
144
+ const DATABASE_CONFIG = Symbol("database-config");
145
+ const dbConfig = {
146
+ host: "localhost",
147
+ port: 5432,
148
+ database: "myapp"
149
+ };
150
+
151
+ container.addConstant(DATABASE_CONFIG, dbConfig);
152
+
153
+ // Retrieve constants
154
+ const apiUrl = container.getConstant<string>("API_URL");
155
+ const maxRetries = container.getConstant<number>("MAX_RETRIES");
156
+ const config = container.getConstant<typeof dbConfig>(DATABASE_CONFIG);
157
+
158
+ console.log(apiUrl); // "https://api.example.com"
159
+ console.log(maxRetries); // 3
160
+ console.log(config.host); // "localhost"
161
+ ```
162
+
163
+ ### Advanced Usage with Mixed Dependencies
164
+
165
+ ```typescript
166
+ import { Container } from '@ooneex/container';
167
+
168
+ const container = new Container();
169
+
170
+ const DB_CONFIG = Symbol("db-config");
171
+ const API_URL = "API_URL";
172
+
173
+ interface DatabaseConfig {
174
+ host: string;
175
+ port: number;
176
+ }
177
+
178
+ class ApiService {
179
+ public getEndpoint(): string {
180
+ const apiUrl = container.getConstant<string>(API_URL);
181
+ return `${apiUrl}/users`;
182
+ }
183
+ }
184
+
185
+ class DatabaseService {
186
+ public connect(): string {
187
+ const config = container.getConstant<DatabaseConfig>(DB_CONFIG);
188
+ return `Connected to ${config.host}:${config.port}`;
189
+ }
190
+ }
191
+
192
+ class UserService {
193
+ private api: ApiService;
194
+ private db: DatabaseService;
195
+
196
+ constructor() {
197
+ this.api = container.get(ApiService);
198
+ this.db = container.get(DatabaseService);
199
+ }
200
+
201
+ public processUser(): string {
202
+ const endpoint = this.api.getEndpoint();
203
+ const connection = this.db.connect();
204
+ return `Processing user via ${endpoint} with ${connection}`;
205
+ }
206
+ }
207
+
208
+ // Register constants
209
+ container.addConstant(DB_CONFIG, { host: "localhost", port: 5432 });
210
+ container.addConstant(API_URL, "https://api.example.com");
211
+
212
+ // Register services
213
+ container.add(ApiService);
214
+ container.add(DatabaseService);
215
+ container.add(UserService);
216
+
217
+ // Use the services
218
+ const userService = container.get(UserService);
219
+ console.log(userService.processUser());
220
+ ```
221
+
222
+ ## API Reference
223
+
224
+ ### `Container` Class
225
+
226
+ The main dependency injection container class.
227
+
228
+ #### Service Methods
229
+
230
+ ##### `add(target: Constructor, scope?: EContainerScope): void`
231
+ Registers a class constructor in the container with optional scoping.
232
+
233
+ **Parameters:**
234
+ - `target` - The class constructor to register
235
+ - `scope` - The lifecycle scope (default: `EContainerScope.Singleton`)
236
+
237
+ **Example:**
238
+ ```typescript
239
+ container.add(DatabaseService);
240
+ container.add(LoggerService, EContainerScope.Transient);
241
+ container.add(RequestService, EContainerScope.Request);
242
+ ```
243
+
244
+ ##### `get<T>(target: Constructor<T>): T`
245
+ Resolves and returns an instance of the registered class.
246
+
247
+ **Parameters:**
248
+ - `target` - The class constructor to resolve
249
+
250
+ **Returns:** Instance of the requested class
251
+
252
+ **Throws:** `ContainerException` if the service is not registered
253
+
254
+ **Example:**
255
+ ```typescript
256
+ const service = container.get(DatabaseService);
257
+ service.connect();
258
+ ```
259
+
260
+ ##### `has(target: Constructor): boolean`
261
+ Checks if a service is registered in the container.
262
+
263
+ **Parameters:**
264
+ - `target` - The class constructor to check
265
+
266
+ **Returns:** `true` if registered, `false` otherwise
267
+
268
+ **Example:**
269
+ ```typescript
270
+ if (container.has(DatabaseService)) {
271
+ const db = container.get(DatabaseService);
272
+ }
273
+ ```
274
+
275
+ ##### `remove(target: Constructor): void`
276
+ Removes a service registration from the container.
277
+
278
+ **Parameters:**
279
+ - `target` - The class constructor to remove
280
+
281
+ **Example:**
282
+ ```typescript
283
+ container.remove(DatabaseService);
284
+ console.log(container.has(DatabaseService)); // false
285
+ ```
286
+
287
+ #### Constants Methods
288
+
289
+ ##### `addConstant
290
+ <T>(identifier: string | symbol, value: T): void`
291
+ Registers a constant value in the container.
292
+
293
+ **Parameters:**
294
+ - `identifier` - String or symbol identifier for the constant
295
+ - `value` - The constant value to store
296
+
297
+ **Example:**
298
+ ```typescript
299
+ container.addConstant("API_KEY", "secret-key-123");
300
+ const CONFIG_SYMBOL = Symbol("config");
301
+ container.addConstant(CONFIG_SYMBOL, { env: "production" });
302
+ ```
303
+
304
+ ##### `getConstant<T>(identifier: string | symbol): T`
305
+ Retrieves a constant value from the container.
306
+
307
+ **Parameters:**
308
+ - `identifier` - String or symbol identifier for the constant
309
+
310
+ **Returns:** The stored constant value
311
+
312
+ **Throws:** `ContainerException` if the constant is not found
313
+
314
+ **Example:**
315
+ ```typescript
316
+ const apiKey = container.getConstant<string>("API_KEY");
317
+ const config = container.getConstant<Config>(CONFIG_SYMBOL);
318
+ ```
319
+
320
+ ##### `hasConstant(identifier: string | symbol): boolean`
321
+ Checks if a constant is registered in the container.
322
+
323
+ **Parameters:**
324
+ - `identifier` - String or symbol identifier to check
325
+
326
+ **Returns:** `true` if the constant exists, `false` otherwise
327
+
328
+ **Example:**
329
+ ```typescript
330
+ if (container.hasConstant("API_KEY")) {
331
+ const key = container.getConstant<string>("API_KEY");
332
+ }
333
+ ```
334
+
335
+ ##### `removeConstant(identifier: string | symbol): void`
336
+ Removes a constant from the container.
337
+
338
+ **Parameters:**
339
+ - `identifier` - String or symbol identifier to remove
340
+
341
+ **Example:**
342
+ ```typescript
343
+ container.removeConstant("API_KEY");
344
+ console.log(container.hasConstant("API_KEY")); // false
345
+ ```
346
+
347
+ ### `EContainerScope` Enum
348
+
349
+ Defines the lifecycle
350
+ scopes for service instances.
351
+
352
+ #### Values
353
+
354
+ ##### `EContainerScope.Singleton`
355
+ Creates a single instance that is reused for all requests (default behavior).
356
+
357
+ **Example:**
358
+ ```typescript
359
+ container.add(DatabaseService, EContainerScope.Singleton);
360
+ ```
361
+
362
+ ##### `EContainerScope.Transient`
363
+ Creates a new instance for every request.
364
+
365
+ **Example:**
366
+ ```typescript
367
+ container.add(RequestIdService, EContainerScope.Transient);
368
+ ```
369
+
370
+ ##### `EContainerScope.Request`
371
+ Creates one instance per request scope (useful in web applications).
372
+
373
+ **Example:**
374
+ ```typescript
375
+ container.add(UserContextService, EContainerScope.Request);
376
+ ```
377
+
378
+ ### `IContainer` Interface
379
+
380
+ Interface defining the contract for dependency injection containers.
381
+
382
+ **Example:**
383
+ ```typescript
384
+ import { IContainer } from '@ooneex/container';
385
+
386
+ class CustomContainer implements IContainer {
387
+ // Implement all required methods
388
+ add(target: Constructor, scope?: EContainerScope): void {
389
+ // Custom implementation
390
+ }
391
+
392
+ get<T>(target: Constructor<T>): T {
393
+ // Custom implementation
394
+ }
395
+
396
+ // ... other methods
397
+ }
398
+ ```
399
+
400
+ ### `ContainerException` Class
401
+
402
+ Exception thrown when container operations fail.
403
+
404
+ **Properties:**
405
+ - Extends the base `Exception` class from `@ooneex/exception`
406
+ - Contains detailed error information and context
407
+ - HTTP status code set to `500 Internal Server Error`
408
+
409
+ **Example:**
410
+ ```typescript
411
+ try {
412
+ const service = container.get(UnregisteredService);
413
+ } catch (error) {
414
+ if (error instanceof ContainerException) {
415
+ console.log(error.message); // "Failed to resolve dependency: UnregisteredService"
416
+ console.log(error.status); // 500
417
+ }
418
+ }
419
+ ```
420
+
421
+ ## Error Handling
422
+
423
+ The container provides comprehensive error handling through the `ContainerException` class:
424
+
425
+ ```typescript
426
+ import { Container, ContainerException } from '@ooneex/container';
427
+
428
+ const container = new Container();
429
+
430
+ // Service not registered
431
+ try {
432
+ const service = container.get(UnknownService);
433
+ } catch (error) {
434
+ if (error instanceof ContainerException) {
435
+ console.log(`Service error: ${error.message}`);
436
+ }
437
+ }
438
+
439
+ // Constant not found
440
+ try {
441
+ const value = container.getConstant("MISSING_CONSTANT");
442
+ } catch (error) {
443
+ if (error instanceof ContainerException) {
444
+ console.log(`Constant error: ${error.message}`);
445
+ }
446
+ }
447
+ ```
448
+
449
+ ## Best Practices
450
+
451
+ ### 1. Use Symbols for Internal Constants
452
+ ```typescript
453
+ // Use symbols to avoid naming conflicts
454
+ const DATABASE_CONFIG = Symbol("database-config");
455
+ container.addConstant(DATABASE_CONFIG, config);
456
+ ```
457
+
458
+ ### 2. Check Registration Before Use
459
+ ```typescript
460
+ if (!container.has(OptionalService)) {
461
+ container.add(OptionalService);
462
+ }
463
+ ```
464
+
465
+ ### 3. Handle Exceptions Gracefully
466
+ ```typescript
467
+ try {
468
+ const service = container.get(CriticalService);
469
+ return service.process();
470
+ } catch (error) {
471
+ if (error instanceof ContainerException) {
472
+ // Log error and provide fallback
473
+ console.error("Service unavailable:", error.message);
474
+ return defaultResult;
475
+ }
476
+ throw error;
477
+ }
478
+ ```
479
+
480
+ ### 4. Use Appropriate Scoping
481
+ ```typescript
482
+ // Singleton for shared resources
483
+ container.add(DatabaseConnection, EContainerScope.Singleton);
484
+
485
+ // Transient for stateful services
486
+ container.add(UserSession, EContainerScope.Transient);
487
+
488
+ // Request scope for web request context
489
+ container.add(RequestContext, EContainerScope.Request);
490
+ ```
491
+
492
+ ### 5. Organize Dependencies
493
+ ```typescript
494
+ // Group related services and constants
495
+ const setupDatabase = (container: Container) => {
496
+ const DB_CONFIG = Symbol("db-config");
497
+ container.addConstant(DB_CONFIG, databaseConfig);
498
+ container.add(DatabaseService);
499
+ container.add(UserRepository);
500
+ };
501
+
502
+ const setupApi = (container: Container) => {
503
+ container.addConstant("API_BASE_URL", process.env.API_URL);
504
+ container.add(ApiClient);
505
+ container.add(AuthService);
506
+ };
507
+ ```
508
+
509
+ ## License
510
+
511
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
512
+
513
+ ## Copyright
514
+
515
+ Copyright (c) 2025 Ooneex
516
+
517
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
518
+
519
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
520
+
521
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
522
+
523
+ ## Contributing
524
+
525
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
526
+
527
+ ### Development Setup
528
+
529
+ 1. Clone the repository
530
+ 2. Install dependencies: `bun install`
531
+ 3. Run tests: `bun run test`
532
+ 4. Build the project: `bun run build`
533
+
534
+ ### Guidelines
535
+
536
+ - Write tests for new features
537
+ - Follow the existing code style
538
+ - Update documentation for API changes
539
+ - Ensure all tests pass before submitting PR
540
+
541
+ ---
542
+
543
+ Made with ❤️ by the Ooneex team
@@ -0,0 +1,61 @@
1
+ import { inject } from "inversify";
2
+ /** biome-ignore-all lint/suspicious/noExplicitAny: trust me */
3
+ declare enum EContainerScope {
4
+ Singleton = "singleton",
5
+ Transient = "transient",
6
+ Request = "request"
7
+ }
8
+ interface IContainer {
9
+ add: (target: new (...args: any[]) => any, scope?: EContainerScope) => void;
10
+ get: <T>(target: (new (...args: any[]) => T) | string) => T;
11
+ has: (target: (new (...args: any[]) => any) | string) => boolean;
12
+ remove: (target: (new (...args: any[]) => any) | string) => void;
13
+ addConstant: <T>(identifier: string | symbol, value: T) => void;
14
+ getConstant: <T>(identifier: string | symbol) => T;
15
+ hasConstant: (identifier: string | symbol) => boolean;
16
+ removeConstant(identifier: string | symbol): void;
17
+ addAlias<T>(alias: string, target: new (...args: any[]) => T): void;
18
+ }
19
+ declare class Container implements IContainer {
20
+ private alias;
21
+ add(target: new (...args: any[]) => any, scope?: EContainerScope): void;
22
+ private resolveAlias;
23
+ get<T>(target: (new (...args: any[]) => T) | string): T;
24
+ has(target: (new (...args: any[]) => unknown) | string): boolean;
25
+ remove(target: (new (...args: unknown[]) => unknown) | string): void;
26
+ addConstant<T>(identifier: string | symbol, value: T): void;
27
+ getConstant<T>(identifier: string | symbol): T;
28
+ hasConstant(identifier: string | symbol): boolean;
29
+ removeConstant(identifier: string | symbol): void;
30
+ addAlias<T>(alias: string, target: new (...args: any[]) => T): void;
31
+ }
32
+ declare const container: Container;
33
+ import { Exception } from "@ooneex/exception";
34
+ declare class ContainerException extends Exception {
35
+ constructor(message: string, data?: Record<string, unknown>);
36
+ }
37
+ import { AnalyticsClassType } from "@ooneex/analytics";
38
+ import { CacheClassType } from "@ooneex/cache";
39
+ import { CronClassType } from "@ooneex/cron";
40
+ import { DatabaseClassType } from "@ooneex/database";
41
+ import { LoggerClassType } from "@ooneex/logger";
42
+ import { MailerClassType } from "@ooneex/mailer";
43
+ import { MiddlewareClassType } from "@ooneex/middleware";
44
+ import { PermissionClassType } from "@ooneex/permission";
45
+ import { RepositoryClassType } from "@ooneex/repository";
46
+ import { ServiceClassType } from "@ooneex/service";
47
+ import { StorageClassType } from "@ooneex/storage";
48
+ declare const decorator: {
49
+ analytics: (scope?: EContainerScope) => (target: AnalyticsClassType) => void;
50
+ service: (scope?: EContainerScope) => (target: ServiceClassType) => void;
51
+ cache: (scope?: EContainerScope) => (target: CacheClassType) => void;
52
+ database: (scope?: EContainerScope) => (target: DatabaseClassType) => void;
53
+ logger: (scope?: EContainerScope) => (target: LoggerClassType) => void;
54
+ mailer: (scope?: EContainerScope) => (target: MailerClassType) => void;
55
+ middleware: (scope?: EContainerScope) => (target: MiddlewareClassType) => void;
56
+ repository: (scope?: EContainerScope) => (target: RepositoryClassType) => void;
57
+ storage: (scope?: EContainerScope) => (target: StorageClassType) => void;
58
+ cron: (scope?: EContainerScope) => (target: CronClassType) => void;
59
+ permission: (scope?: EContainerScope) => (target: PermissionClassType) => void;
60
+ };
61
+ export { inject, decorator, container, IContainer, EContainerScope, ContainerException, Container };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import{inject as E}from"inversify";import{Container as y}from"inversify";import{Exception as l}from"@ooneex/exception";import{HttpStatus as t}from"@ooneex/http-status";class e extends l{constructor(n,o={}){super(n,{status:t.Code.InternalServerError,data:o});this.name="ContainerException"}}var r;((a)=>{a.Singleton="singleton";a.Transient="transient";a.Request="request"})(r||={});var s=new y;class p{alias={};add(n,o="singleton"){try{s.unbind(n)}catch{}let m=s.bind(n).toSelf();switch(o){case"request":m.inRequestScope();break;case"transient":m.inTransientScope();break;default:m.inSingletonScope()}}resolveAlias(n,o=!0){if(typeof n==="string"){let m=this.alias[n];if(!m){if(o)throw new e(`Failed to resolve alias: ${n}`);return null}return m}return n}get(n){let o=this.resolveAlias(n,!0);try{return s.get(o)}catch(m){throw new e(`Failed to resolve dependency: ${typeof n==="string"?n:n.name}`)}}has(n){let o=this.resolveAlias(n,!1);if(o===null)return!1;return s.isBound(o)}remove(n){let o=this.resolveAlias(n,!0);if(o&&s.isBound(o))s.unbind(o)}addConstant(n,o){try{s.unbind(n)}catch{}s.bind(n).toConstantValue(o)}getConstant(n){try{return s.get(n)}catch(o){throw new e(`Failed to resolve constant: ${n.toString()}`)}}hasConstant(n){return s.isBound(n)}removeConstant(n){if(s.isBound(n))s.unbind(n)}addAlias(n,o){this.alias[n]=o}}var i=new p;var W={analytics:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Analytics")&&!o.name.endsWith("AnalyticsAdapter"))throw new e(`Class name "${o.name}" must end with "Analytics" or "AnalyticsAdapter"`);i.add(o,n)}},service:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Service"))throw new e(`Class name "${o.name}" must end with "Service"`);i.add(o,n)}},cache:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Cache"))throw new e(`Class name "${o.name}" must end with "Cache"`);i.add(o,n)}},database:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Database"))throw new e(`Class name "${o.name}" must end with "Database"`);i.add(o,n)}},logger:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Logger"))throw new e(`Class name "${o.name}" must end with "Logger"`);i.add(o,n)}},mailer:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Mailer")&&!o.name.endsWith("MailerAdapter"))throw new e(`Class name "${o.name}" must end with "Mailer" or "MailerAdapter"`);i.add(o,n)}},middleware:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Middleware"))throw new e(`Class name "${o.name}" must end with "Middleware"`);i.add(o,n)}},repository:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Repository"))throw new e(`Class name "${o.name}" must end with "Repository"`);i.add(o,n)}},storage:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Storage"))throw new e(`Class name "${o.name}" must end with "Storage"`);i.add(o,n)}},cron:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Cron"))throw new e(`Class name "${o.name}" must end with "Cron"`);i.add(o,n)}},permission:(n="singleton")=>{return(o)=>{if(!o.name.endsWith("Permission"))throw new e(`Class name "${o.name}" must end with "Permission"`);i.add(o,n)}}};export{E as inject,W as decorator,i as container,r as EContainerScope,e as ContainerException,p as Container};
2
+
3
+ //# debugId=5D96BB24FDB8E1BC64756E2164756E21
@@ -0,0 +1,14 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["src/index.ts", "src/Container.ts", "src/ContainerException.ts", "src/types.ts", "src/decorators.ts"],
4
+ "sourcesContent": [
5
+ "export { inject } from \"inversify\";\nexport * from \"./Container\";\nexport * from \"./ContainerException\";\nexport * from \"./decorators\";\nexport * from \"./types\";\n",
6
+ "/** biome-ignore-all lint/suspicious/noExplicitAny: trust me */\n\nimport { Container as InversifyContainer } from \"inversify\";\nimport { ContainerException } from \"./ContainerException\";\nimport { EContainerScope, type IContainer } from \"./types\";\n\n// Shared DI container instance across all Container instances\nconst sharedDI = new InversifyContainer();\n\nexport class Container implements IContainer {\n private alias: Record<string, any> = {};\n\n public add(target: new (...args: any[]) => any, scope: EContainerScope = EContainerScope.Singleton): void {\n try {\n sharedDI.unbind(target);\n } catch {}\n\n const binding = sharedDI.bind(target).toSelf();\n\n switch (scope) {\n case EContainerScope.Request:\n binding.inRequestScope();\n break;\n case EContainerScope.Transient:\n binding.inTransientScope();\n break;\n default:\n binding.inSingletonScope();\n }\n }\n\n private resolveAlias<T>(\n target: (new (...args: any[]) => T) | string,\n throwOnMissing = true,\n ): (new (...args: any[]) => T) | null {\n if (typeof target === \"string\") {\n const aliasedTarget = this.alias[target];\n if (!aliasedTarget) {\n if (throwOnMissing) {\n throw new ContainerException(`Failed to resolve alias: ${target}`);\n }\n return null;\n }\n return aliasedTarget as new (\n ...args: any[]\n ) => T;\n }\n return target as new (\n ...args: any[]\n ) => T;\n }\n\n public get<T>(target: (new (...args: any[]) => T) | string): T {\n const resolvedTarget = this.resolveAlias(target, true);\n\n try {\n return sharedDI.get<T>(resolvedTarget as new (...args: any[]) => T);\n } catch (_e) {\n throw new ContainerException(\n `Failed to resolve dependency: ${typeof target === \"string\" ? target : target.name}`,\n );\n }\n }\n\n public has(target: (new (...args: any[]) => unknown) | string): boolean {\n const resolvedTarget = this.resolveAlias(target, false);\n if (resolvedTarget === null) {\n return false;\n }\n return sharedDI.isBound(resolvedTarget);\n }\n\n public remove(target: (new (...args: unknown[]) => unknown) | string): void {\n const resolvedTarget = this.resolveAlias(target, true);\n if (resolvedTarget && sharedDI.isBound(resolvedTarget)) {\n sharedDI.unbind(resolvedTarget);\n }\n }\n\n public addConstant<T>(identifier: string | symbol, value: T): void {\n try {\n sharedDI.unbind(identifier);\n } catch {}\n\n sharedDI.bind<T>(identifier).toConstantValue(value);\n }\n\n public getConstant<T>(identifier: string | symbol): T {\n try {\n return sharedDI.get<T>(identifier);\n } catch (_e) {\n throw new ContainerException(`Failed to resolve constant: ${identifier.toString()}`);\n }\n }\n\n public hasConstant(identifier: string | symbol): boolean {\n return sharedDI.isBound(identifier);\n }\n\n public removeConstant(identifier: string | symbol): void {\n if (sharedDI.isBound(identifier)) {\n sharedDI.unbind(identifier);\n }\n }\n\n public addAlias<T>(alias: string, target: new (...args: any[]) => T): void {\n this.alias[alias] = target;\n }\n}\n\nexport const container: Container = new Container();\n",
7
+ "import { Exception } from \"@ooneex/exception\";\nimport { HttpStatus } from \"@ooneex/http-status\";\n\nexport class ContainerException extends Exception {\n constructor(message: string, data: Record<string, unknown> = {}) {\n super(message, {\n status: HttpStatus.Code.InternalServerError,\n data,\n });\n this.name = \"ContainerException\";\n }\n}\n",
8
+ "/** biome-ignore-all lint/suspicious/noExplicitAny: trust me */\n\nexport enum EContainerScope {\n Singleton = \"singleton\",\n Transient = \"transient\",\n Request = \"request\",\n}\n\nexport interface IContainer {\n add: (target: new (...args: any[]) => any, scope?: EContainerScope) => void;\n get: <T>(target: (new (...args: any[]) => T) | string) => T;\n has: (target: (new (...args: any[]) => any) | string) => boolean;\n remove: (target: (new (...args: any[]) => any) | string) => void;\n addConstant: <T>(identifier: string | symbol, value: T) => void;\n getConstant: <T>(identifier: string | symbol) => T;\n hasConstant: (identifier: string | symbol) => boolean;\n removeConstant(identifier: string | symbol): void;\n addAlias<T>(alias: string, target: new (...args: any[]) => T): void;\n}\n",
9
+ "import type { AnalyticsClassType } from \"@ooneex/analytics\";\nimport type { CacheClassType } from \"@ooneex/cache\";\nimport type { CronClassType } from \"@ooneex/cron\";\nimport type { DatabaseClassType } from \"@ooneex/database\";\nimport type { LoggerClassType } from \"@ooneex/logger\";\nimport type { MailerClassType } from \"@ooneex/mailer\";\nimport type { MiddlewareClassType } from \"@ooneex/middleware\";\nimport type { PermissionClassType } from \"@ooneex/permission\";\nimport type { RepositoryClassType } from \"@ooneex/repository\";\nimport type { ServiceClassType } from \"@ooneex/service\";\nimport type { StorageClassType } from \"@ooneex/storage\";\nimport { container } from \"./Container\";\nimport { ContainerException } from \"./ContainerException\";\nimport { EContainerScope } from \"./types\";\n\nexport const decorator = {\n analytics: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: AnalyticsClassType): void => {\n if (!target.name.endsWith(\"Analytics\") && !target.name.endsWith(\"AnalyticsAdapter\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Analytics\" or \"AnalyticsAdapter\"`);\n }\n container.add(target, scope);\n };\n },\n service: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: ServiceClassType): void => {\n if (!target.name.endsWith(\"Service\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Service\"`);\n }\n container.add(target, scope);\n };\n },\n cache: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: CacheClassType): void => {\n if (!target.name.endsWith(\"Cache\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Cache\"`);\n }\n container.add(target, scope);\n };\n },\n database: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: DatabaseClassType): void => {\n if (!target.name.endsWith(\"Database\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Database\"`);\n }\n container.add(target, scope);\n };\n },\n logger: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: LoggerClassType): void => {\n if (!target.name.endsWith(\"Logger\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Logger\"`);\n }\n container.add(target, scope);\n };\n },\n mailer: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: MailerClassType): void => {\n if (!target.name.endsWith(\"Mailer\") && !target.name.endsWith(\"MailerAdapter\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Mailer\" or \"MailerAdapter\"`);\n }\n container.add(target, scope);\n };\n },\n middleware: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: MiddlewareClassType): void => {\n if (!target.name.endsWith(\"Middleware\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Middleware\"`);\n }\n container.add(target, scope);\n };\n },\n repository: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: RepositoryClassType): void => {\n if (!target.name.endsWith(\"Repository\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Repository\"`);\n }\n container.add(target, scope);\n };\n },\n storage: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: StorageClassType): void => {\n if (!target.name.endsWith(\"Storage\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Storage\"`);\n }\n container.add(target, scope);\n };\n },\n cron: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: CronClassType): void => {\n if (!target.name.endsWith(\"Cron\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Cron\"`);\n }\n container.add(target, scope);\n\n // Create own container\n };\n },\n permission: (scope: EContainerScope = EContainerScope.Singleton) => {\n return (target: PermissionClassType): void => {\n if (!target.name.endsWith(\"Permission\")) {\n throw new ContainerException(`Class name \"${target.name}\" must end with \"Permission\"`);\n }\n container.add(target, scope);\n };\n },\n};\n"
10
+ ],
11
+ "mappings": "AAAA,iBAAS,kBCET,oBAAS,kBCFT,oBAAS,0BACT,qBAAS,4BAEF,MAAM,UAA2B,CAAU,CAChD,WAAW,CAAC,EAAiB,EAAgC,CAAC,EAAG,CAC/D,MAAM,EAAS,CACb,OAAQ,EAAW,KAAK,oBACxB,MACF,CAAC,EACD,KAAK,KAAO,qBAEhB,CCTO,IAAK,GAAL,CAAK,IAAL,CACL,YAAY,YACZ,YAAY,YACZ,UAAU,YAHA,QFKZ,IAAM,EAAW,IAAI,EAEd,MAAM,CAAgC,CACnC,MAA6B,CAAC,EAE/B,GAAG,CAAC,EAAqC,cAA0D,CACxG,GAAI,CACF,EAAS,OAAO,CAAM,EACtB,KAAM,EAER,IAAM,EAAU,EAAS,KAAK,CAAM,EAAE,OAAO,EAE7C,OAAQ,iBAEJ,EAAQ,eAAe,EACvB,sBAEA,EAAQ,iBAAiB,EACzB,cAEA,EAAQ,iBAAiB,GAIvB,YAAe,CACrB,EACA,EAAiB,GACmB,CACpC,GAAI,OAAO,IAAW,SAAU,CAC9B,IAAM,EAAgB,KAAK,MAAM,GACjC,GAAI,CAAC,EAAe,CAClB,GAAI,EACF,MAAM,IAAI,EAAmB,4BAA4B,GAAQ,EAEnE,OAAO,KAET,OAAO,EAIT,OAAO,EAKF,GAAM,CAAC,EAAiD,CAC7D,IAAM,EAAiB,KAAK,aAAa,EAAQ,EAAI,EAErD,GAAI,CACF,OAAO,EAAS,IAAO,CAA2C,EAClE,MAAO,EAAI,CACX,MAAM,IAAI,EACR,iCAAiC,OAAO,IAAW,SAAW,EAAS,EAAO,MAChF,GAIG,GAAG,CAAC,EAA6D,CACtE,IAAM,EAAiB,KAAK,aAAa,EAAQ,EAAK,EACtD,GAAI,IAAmB,KACrB,MAAO,GAET,OAAO,EAAS,QAAQ,CAAc,EAGjC,MAAM,CAAC,EAA8D,CAC1E,I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AClE,MAAO,CAAC,IAAsC,CAC5C,GAAI,CAAC,EAAO,KAAK,SAAS,YAAY,EACpC,MAAM,IAAI,EAAmB,eAAe,EAAO,kCAAkC,EAEvF,EAAU,IAAI,EAAQ,CAAK,GAGjC",
12
+ "debugId": "5D96BB24FDB8E1BC64756E2164756E21",
13
+ "names": []
14
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@ooneex/container",
3
+ "description": "",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "LICENSE",
9
+ "README.md",
10
+ "package.json"
11
+ ],
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "license": "MIT",
24
+ "scripts": {
25
+ "test": "bun test tests",
26
+ "build": "bunup",
27
+ "lint": "tsgo --noEmit && bunx biome lint",
28
+ "publish:prod": "bun publish --tolerate-republish --access public",
29
+ "publish:pack": "bun pm pack --destination ./dist",
30
+ "publish:dry": "bun publish --dry-run"
31
+ },
32
+ "devDependencies": {
33
+ "@ooneex/analytics": "0.0.1",
34
+ "@ooneex/cache": "0.0.1",
35
+ "@ooneex/cron": "0.0.1",
36
+ "@ooneex/database": "0.0.1",
37
+ "@ooneex/logger": "0.0.1",
38
+ "@ooneex/mailer": "0.0.1",
39
+ "@ooneex/middleware": "0.0.1",
40
+ "@ooneex/permission": "0.0.1",
41
+ "@ooneex/repository": "0.0.1",
42
+ "@ooneex/service": "0.0.1",
43
+ "@ooneex/storage": "0.0.1"
44
+ },
45
+ "peerDependencies": {},
46
+ "dependencies": {
47
+ "@ooneex/exception": "0.0.1",
48
+ "@ooneex/http-status": "0.0.1",
49
+ "inversify": "^7.10.4"
50
+ }
51
+ }