@tsed/di 8.18.1 → 8.19.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 (89) hide show
  1. package/lib/esm/common/decorators/autoInjectable.js +28 -9
  2. package/lib/esm/common/decorators/constant.js +26 -22
  3. package/lib/esm/common/decorators/controller.js +40 -20
  4. package/lib/esm/common/decorators/injectable.js +30 -10
  5. package/lib/esm/common/decorators/intercept.js +41 -3
  6. package/lib/esm/common/decorators/interceptor.js +31 -4
  7. package/lib/esm/common/decorators/module.js +36 -5
  8. package/lib/esm/common/decorators/opts.js +20 -12
  9. package/lib/esm/common/decorators/overrideProvider.js +38 -4
  10. package/lib/esm/common/decorators/scope.js +32 -3
  11. package/lib/esm/common/decorators/service.js +24 -4
  12. package/lib/esm/common/decorators/useOpts.js +21 -13
  13. package/lib/esm/common/decorators/value.js +28 -22
  14. package/lib/esm/common/domain/Container.js +20 -0
  15. package/lib/esm/common/domain/ContextLogger.js +21 -0
  16. package/lib/esm/common/domain/ControllerProvider.js +22 -0
  17. package/lib/esm/common/domain/DIContext.js +22 -0
  18. package/lib/esm/common/domain/InjectablePropertyType.js +16 -0
  19. package/lib/esm/common/domain/LocalsContainer.js +21 -0
  20. package/lib/esm/common/domain/Provider.js +19 -0
  21. package/lib/esm/common/domain/ProviderScope.js +25 -0
  22. package/lib/esm/common/domain/ProviderType.js +25 -0
  23. package/lib/esm/common/errors/InjectionError.js +24 -0
  24. package/lib/esm/common/errors/InvalidPropertyTokenError.js +15 -0
  25. package/lib/esm/common/fn/inject.js +19 -6
  26. package/lib/esm/common/fn/injectMany.js +24 -6
  27. package/lib/esm/common/fn/injectable.js +57 -0
  28. package/lib/esm/common/fn/injector.js +21 -2
  29. package/lib/esm/common/fn/lazyInject.js +48 -1
  30. package/lib/esm/common/fn/localsContainer.js +31 -2
  31. package/lib/esm/common/fn/logger.js +15 -1
  32. package/lib/esm/common/services/DIConfiguration.js +24 -0
  33. package/lib/esm/common/services/DILogger.js +23 -0
  34. package/lib/esm/common/services/InjectorService.js +89 -43
  35. package/lib/types/common/decorators/autoInjectable.d.ts +31 -10
  36. package/lib/types/common/decorators/configuration.d.ts +32 -2
  37. package/lib/types/common/decorators/constant.d.ts +26 -22
  38. package/lib/types/common/decorators/controller.d.ts +40 -20
  39. package/lib/types/common/decorators/inject.d.ts +29 -7
  40. package/lib/types/common/decorators/injectable.d.ts +30 -10
  41. package/lib/types/common/decorators/intercept.d.ts +41 -3
  42. package/lib/types/common/decorators/interceptor.d.ts +31 -4
  43. package/lib/types/common/decorators/lazyInject.d.ts +43 -9
  44. package/lib/types/common/decorators/module.d.ts +36 -5
  45. package/lib/types/common/decorators/opts.d.ts +20 -12
  46. package/lib/types/common/decorators/overrideProvider.d.ts +38 -4
  47. package/lib/types/common/decorators/scope.d.ts +32 -3
  48. package/lib/types/common/decorators/service.d.ts +24 -4
  49. package/lib/types/common/decorators/useOpts.d.ts +21 -13
  50. package/lib/types/common/decorators/value.d.ts +28 -22
  51. package/lib/types/common/domain/Container.d.ts +20 -0
  52. package/lib/types/common/domain/ContextLogger.d.ts +26 -0
  53. package/lib/types/common/domain/ControllerProvider.d.ts +29 -0
  54. package/lib/types/common/domain/DIContext.d.ts +27 -0
  55. package/lib/types/common/domain/InjectablePropertyType.d.ts +16 -0
  56. package/lib/types/common/domain/LocalsContainer.d.ts +21 -0
  57. package/lib/types/common/domain/Provider.d.ts +25 -0
  58. package/lib/types/common/domain/ProviderScope.d.ts +25 -0
  59. package/lib/types/common/domain/ProviderType.d.ts +25 -0
  60. package/lib/types/common/errors/InjectionError.d.ts +24 -0
  61. package/lib/types/common/errors/InvalidPropertyTokenError.d.ts +15 -0
  62. package/lib/types/common/fn/configuration.d.ts +31 -0
  63. package/lib/types/common/fn/constant.d.ts +22 -0
  64. package/lib/types/common/fn/inject.d.ts +19 -6
  65. package/lib/types/common/fn/injectMany.d.ts +24 -6
  66. package/lib/types/common/fn/injectable.d.ts +57 -0
  67. package/lib/types/common/fn/injector.d.ts +21 -2
  68. package/lib/types/common/fn/lazyInject.d.ts +48 -1
  69. package/lib/types/common/fn/localsContainer.d.ts +31 -2
  70. package/lib/types/common/fn/logger.d.ts +15 -1
  71. package/lib/types/common/fn/refValue.d.ts +15 -6
  72. package/lib/types/common/interfaces/AlterRunInContext.d.ts +26 -0
  73. package/lib/types/common/interfaces/DILogger.d.ts +36 -0
  74. package/lib/types/common/interfaces/DILoggerOptions.d.ts +23 -0
  75. package/lib/types/common/interfaces/ImportTokenProviderOpts.d.ts +43 -0
  76. package/lib/types/common/interfaces/InterceptorContext.d.ts +35 -0
  77. package/lib/types/common/interfaces/InterceptorMethods.d.ts +27 -0
  78. package/lib/types/common/interfaces/InvokeOptions.d.ts +8 -0
  79. package/lib/types/common/interfaces/OnDestroy.d.ts +22 -0
  80. package/lib/types/common/interfaces/OnInit.d.ts +22 -0
  81. package/lib/types/common/interfaces/ProviderOpts.d.ts +31 -0
  82. package/lib/types/common/interfaces/ResolvedInvokeOptions.d.ts +9 -0
  83. package/lib/types/common/interfaces/TokenProvider.d.ts +32 -2
  84. package/lib/types/common/interfaces/TokenRoute.d.ts +16 -0
  85. package/lib/types/common/services/DIConfiguration.d.ts +24 -0
  86. package/lib/types/common/services/DILogger.d.ts +28 -0
  87. package/lib/types/common/services/InjectorService.d.ts +89 -43
  88. package/lib/types/node/utils/asyncHookContext.d.ts +0 -1
  89. package/package.json +6 -6
@@ -1,3 +1,29 @@
1
+ /**
2
+ * Interface for customizing the execution context of asynchronous operations.
3
+ *
4
+ * Implement this interface to wrap or modify the async context in which operations run,
5
+ * enabling custom context management, async local storage, or execution wrapping.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * import {Injectable, AlterRunInContext} from "@tsed/di";
11
+ * import {AsyncLocalStorage} from "async_hooks";
12
+ *
13
+ * @Injectable()
14
+ * class CustomContextProvider implements AlterRunInContext {
15
+ * private storage = new AsyncLocalStorage();
16
+ *
17
+ * $alterRunInContext(next: Function) {
18
+ * return () => {
19
+ * return this.storage.run({requestId: generateId()}, next);
20
+ * };
21
+ * }
22
+ * }
23
+ * ```
24
+ *
25
+ * @public
26
+ */
1
27
  export interface AlterRunInContext {
2
28
  $alterRunInContext(next: (...args: unknown[]) => unknown): () => unknown | Promise<() => unknown>;
3
29
  }
@@ -1,3 +1,39 @@
1
+ /**
2
+ * Logger interface for the Dependency Injection system.
3
+ *
4
+ * Defines the contract for logging implementations used throughout Ts.ED's DI framework.
5
+ * Custom logger implementations must conform to this interface to be compatible with the DI system.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * import {DILogger} from "@tsed/di";
11
+ *
12
+ * class CustomLogger implements DILogger {
13
+ * info(...args: any[]) {
14
+ * console.log("[INFO]", ...args);
15
+ * }
16
+ *
17
+ * warn(...args: any[]) {
18
+ * console.warn("[WARN]", ...args);
19
+ * }
20
+ *
21
+ * debug(...args: any[]) {
22
+ * console.debug("[DEBUG]", ...args);
23
+ * }
24
+ *
25
+ * error(...args: any[]) {
26
+ * console.error("[ERROR]", ...args);
27
+ * }
28
+ *
29
+ * trace(...args: any[]) {
30
+ * console.trace("[TRACE]", ...args);
31
+ * }
32
+ * }
33
+ * ```
34
+ *
35
+ * @public
36
+ */
1
37
  export interface DILogger {
2
38
  info(...args: any[]): void | any;
3
39
  warn(...args: any[]): void | any;
@@ -1,3 +1,26 @@
1
+ /**
2
+ * Configuration options for the DI Logger.
3
+ *
4
+ * Controls logging behavior, formatting, and filtering for the Ts.ED logging system.
5
+ * These options can be set in the application configuration under the `logger` property.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * import {Configuration} from "@tsed/di";
11
+ *
12
+ * @Configuration({
13
+ * logger: {
14
+ * level: "debug",
15
+ * format: "%d{yyyy-MM-dd HH:mm:ss} %p %m",
16
+ * disableRoutesSummary: false
17
+ * }
18
+ * })
19
+ * class Server {}
20
+ * ```
21
+ *
22
+ * @public
23
+ */
1
24
  export interface DILoggerOptions {
2
25
  /**
3
26
  * Enable debug mode. By default debug is false.
@@ -1,19 +1,62 @@
1
1
  import type { AbstractType, Type } from "@tsed/core";
2
2
  import type { TokenProvider } from "./TokenProvider.js";
3
+ /**
4
+ * Options for importing a provider with a predefined instance.
5
+ *
6
+ * @public
7
+ */
3
8
  export type UseImportTokenProviderOpts = {
4
9
  token: TokenProvider;
5
10
  use: unknown;
6
11
  };
12
+ /**
13
+ * Options for importing a provider using a class constructor.
14
+ *
15
+ * @public
16
+ */
7
17
  export type UseClassImportTokenProviderOpts = {
8
18
  token: TokenProvider;
9
19
  useClass: Type | AbstractType<any>;
10
20
  };
21
+ /**
22
+ * Options for importing a provider using a synchronous factory function.
23
+ *
24
+ * @public
25
+ */
11
26
  export type UseFactoryImportTokenProviderOpts = {
12
27
  token: TokenProvider;
13
28
  useFactory: (...args: unknown[]) => unknown;
14
29
  };
30
+ /**
31
+ * Options for importing a provider using an asynchronous factory function.
32
+ *
33
+ * @public
34
+ */
15
35
  export type UseAsyncFactoryImportTokenProviderOpts = {
16
36
  token: TokenProvider;
17
37
  useAsyncFactory: (...args: unknown[]) => Promise<unknown>;
18
38
  };
39
+ /**
40
+ * Union type representing all valid import provider configuration options.
41
+ *
42
+ * Specifies how an imported provider should be created when listed in module imports or configuration.
43
+ * Supports multiple creation strategies: predefined instances, class constructors, and factory functions.
44
+ *
45
+ * ### Usage
46
+ *
47
+ * ```typescript
48
+ * import {Configuration} from "@tsed/di";
49
+ *
50
+ * @Configuration({
51
+ * imports: [
52
+ * {token: MyService, useClass: MyServiceImpl},
53
+ * {token: "CONFIG", useFactory: () => loadConfig()},
54
+ * {token: DatabaseService, useAsyncFactory: async () => await connectDB()}
55
+ * ]
56
+ * })
57
+ * class Server {}
58
+ * ```
59
+ *
60
+ * @public
61
+ */
19
62
  export type ImportTokenProviderOpts = UseImportTokenProviderOpts | UseClassImportTokenProviderOpts | UseFactoryImportTokenProviderOpts | UseAsyncFactoryImportTokenProviderOpts;
@@ -1,7 +1,42 @@
1
1
  import type { Type } from "@tsed/core";
2
+ /**
3
+ * Function signature for proceeding to the next interceptor or method.
4
+ *
5
+ * Call this function in an interceptor to continue the interceptor chain.
6
+ * Pass an error to short-circuit execution and propagate the error.
7
+ *
8
+ * @typeParam T - The return type of the intercepted method
9
+ * @public
10
+ */
2
11
  export interface InterceptorNext {
3
12
  <T>(err?: Error): T;
4
13
  }
14
+ /**
15
+ * Context object passed to interceptors during method execution.
16
+ *
17
+ * Provides access to the target instance, method name, arguments, and control flow
18
+ * for intercepting and modifying method behavior.
19
+ *
20
+ * ### Usage
21
+ *
22
+ * ```typescript
23
+ * import {Interceptor, InterceptorContext, InterceptorMethods} from "@tsed/di";
24
+ *
25
+ * @Interceptor()
26
+ * class LogInterceptor implements InterceptorMethods {
27
+ * intercept(context: InterceptorContext) {
28
+ * console.log("Before:", context.propertyKey);
29
+ * const result = context.next();
30
+ * console.log("After:", result);
31
+ * return result;
32
+ * }
33
+ * }
34
+ * ```
35
+ *
36
+ * @typeParam Klass - The type of the target class
37
+ * @typeParam Opts - The type of interceptor options
38
+ * @public
39
+ */
5
40
  export interface InterceptorContext<Klass = Type, Opts = any> {
6
41
  target: Klass;
7
42
  propertyKey: string | symbol;
@@ -1,4 +1,31 @@
1
1
  import type { InterceptorContext, InterceptorNext } from "./InterceptorContext.js";
2
+ /**
3
+ * Interface for implementing method interceptors.
4
+ *
5
+ * Interceptors can modify method behavior, add logging, handle errors, or implement cross-cutting concerns.
6
+ * Classes decorated with `@Interceptor()` must implement this interface.
7
+ *
8
+ * ### Usage
9
+ *
10
+ * ```typescript
11
+ * import {Interceptor, InterceptorContext, InterceptorMethods} from "@tsed/di";
12
+ *
13
+ * @Interceptor()
14
+ * class CacheInterceptor implements InterceptorMethods {
15
+ * intercept(context: InterceptorContext) {
16
+ * const cacheKey = `${context.propertyKey.toString()}:${JSON.stringify(context.args)}`;
17
+ * if (cache.has(cacheKey)) {
18
+ * return cache.get(cacheKey);
19
+ * }
20
+ * const result = context.next();
21
+ * cache.set(cacheKey, result);
22
+ * return result;
23
+ * }
24
+ * }
25
+ * ```
26
+ *
27
+ * @public
28
+ */
2
29
  export interface InterceptorMethods {
3
30
  intercept(context: InterceptorContext, next?: InterceptorNext): any;
4
31
  }
@@ -1,5 +1,13 @@
1
1
  import type { LocalsContainer } from "../domain/LocalsContainer.js";
2
2
  import { TokenProvider } from "./TokenProvider.js";
3
+ /**
4
+ * Options for invoking and building a provider instance.
5
+ *
6
+ * Controls how the injector resolves dependencies, handles imports, and constructs provider instances.
7
+ * Used when manually invoking the injector to create instances with specific configuration.
8
+ *
9
+ * @public
10
+ */
3
11
  export interface InvokeOptions {
4
12
  /**
5
13
  * Define dependencies to build the provider and inject them in the constructor.
@@ -1,3 +1,25 @@
1
+ /**
2
+ * Lifecycle hook interface for cleanup logic.
3
+ *
4
+ * Implement this interface to execute custom cleanup code when a provider instance is destroyed by the DI container.
5
+ * The `$onDestroy` method is called automatically during application shutdown or when the provider scope ends.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * import {Injectable, OnDestroy} from "@tsed/di";
11
+ *
12
+ * @Injectable()
13
+ * class MyService implements OnDestroy {
14
+ * async $onDestroy() {
15
+ * // Close connections, release resources, etc.
16
+ * await this.disconnect();
17
+ * }
18
+ * }
19
+ * ```
20
+ *
21
+ * @public
22
+ */
1
23
  export interface OnDestroy {
2
24
  $onDestroy(): Promise<any> | void;
3
25
  }
@@ -1,3 +1,25 @@
1
+ /**
2
+ * Lifecycle hook interface for initialization logic.
3
+ *
4
+ * Implement this interface to execute custom initialization code when a provider instance is created by the DI container.
5
+ * The `$onInit` method is called automatically after the instance is constructed and dependencies are injected.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * import {Injectable, OnInit} from "@tsed/di";
11
+ *
12
+ * @Injectable()
13
+ * class MyService implements OnInit {
14
+ * async $onInit() {
15
+ * // Initialize database connection, load configuration, etc.
16
+ * await this.connect();
17
+ * }
18
+ * }
19
+ * ```
20
+ *
21
+ * @public
22
+ */
1
23
  export interface OnInit {
2
24
  $onInit(): Promise<any> | void;
3
25
  }
@@ -2,6 +2,37 @@ import type { Type } from "@tsed/core";
2
2
  import type { ProviderScope } from "../domain/ProviderScope.js";
3
3
  import type { ProviderType } from "../domain/ProviderType.js";
4
4
  import type { TokenProvider } from "./TokenProvider.js";
5
+ /**
6
+ * Configuration options for registering a provider in the DI container.
7
+ *
8
+ * Defines how a provider should be created, managed, and resolved by the injector.
9
+ * Supports multiple creation strategies including class instantiation, factory functions, and predefined values.
10
+ *
11
+ * ### Usage
12
+ *
13
+ * ```typescript
14
+ * // Using a class
15
+ * const opts1: ProviderOpts = {
16
+ * token: MyService,
17
+ * useClass: MyService
18
+ * };
19
+ *
20
+ * // Using a factory
21
+ * const opts2: ProviderOpts = {
22
+ * token: "CONFIG",
23
+ * useFactory: () => loadConfig()
24
+ * };
25
+ *
26
+ * // Using a value
27
+ * const opts3: ProviderOpts = {
28
+ * token: "API_KEY",
29
+ * useValue: "secret-key"
30
+ * };
31
+ * ```
32
+ *
33
+ * @typeParam T - The type of instance provided by this provider
34
+ * @public
35
+ */
5
36
  export interface ProviderOpts<T = any> {
6
37
  /**
7
38
  * An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
@@ -1,6 +1,15 @@
1
1
  import type { LocalsContainer } from "../domain/LocalsContainer.js";
2
2
  import type { Provider } from "../domain/Provider.js";
3
3
  import type { TokenProvider } from "./TokenProvider.js";
4
+ /**
5
+ * Resolved invocation options used internally by the injector.
6
+ *
7
+ * Contains fully resolved dependencies, provider metadata, and construction logic
8
+ * prepared by the injector before instantiating a provider.
9
+ *
10
+ * @internal
11
+ * @public
12
+ */
4
13
  export interface ResolvedInvokeOptions {
5
14
  token: TokenProvider;
6
15
  parent?: TokenProvider;
@@ -1,9 +1,39 @@
1
1
  import type { AbstractType, Type } from "@tsed/core";
2
2
  /**
3
- * A token is a unique identifier for a provider in the dependency injection system.
4
- * It solves the inference problem when using `inject()` function.
3
+ * Factory token type with type inference support.
4
+ *
5
+ * A branded type that enables type inference when using the `inject()` function.
6
+ * This token type carries runtime type information to solve TypeScript's inference limitations in DI scenarios.
7
+ *
8
+ * @typeParam T - The type of value provided by this token
9
+ * @public
5
10
  */
6
11
  export type FactoryTokenProvider<T = any> = T & {
7
12
  readonly __type: "token_factory";
8
13
  };
14
+ /**
15
+ * Union type representing all valid provider tokens in the DI system.
16
+ *
17
+ * A token uniquely identifies a provider in the dependency injection container.
18
+ * Tokens can be strings, symbols, class constructors, or factory tokens with type inference.
19
+ *
20
+ * ### Usage
21
+ *
22
+ * ```typescript
23
+ * // String token
24
+ * const token1: TokenProvider = "MY_SERVICE";
25
+ *
26
+ * // Symbol token
27
+ * const token2: TokenProvider = Symbol.for("MY_SERVICE");
28
+ *
29
+ * // Class token
30
+ * const token3: TokenProvider = MyService;
31
+ *
32
+ * // Factory token with inference
33
+ * const token4 = inject<MyService>();
34
+ * ```
35
+ *
36
+ * @typeParam T - The type of value provided by this token
37
+ * @public
38
+ */
9
39
  export type TokenProvider<T = any> = string | symbol | Type<T> | AbstractType<T> | FactoryTokenProvider<T>;
@@ -1,4 +1,20 @@
1
1
  import { TokenProvider } from "./TokenProvider.js";
2
+ /**
3
+ * Associates a provider token with a route path.
4
+ *
5
+ * Used to map controllers or route handlers to specific URL paths in the routing system.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * const route: TokenRoute = {
11
+ * token: MyController,
12
+ * route: "/api/users"
13
+ * };
14
+ * ```
15
+ *
16
+ * @public
17
+ */
2
18
  export interface TokenRoute {
3
19
  token: TokenProvider;
4
20
  route: string;
@@ -3,6 +3,30 @@ import type { DILoggerOptions } from "../interfaces/DILoggerOptions.js";
3
3
  import type { ImportTokenProviderOpts } from "../interfaces/ImportTokenProviderOpts.js";
4
4
  import type { TokenProvider } from "../interfaces/TokenProvider.js";
5
5
  import type { TokenRoute } from "../interfaces/TokenRoute.js";
6
+ /**
7
+ * Configuration management service for the DI system.
8
+ *
9
+ * Stores and manages application configuration settings including imports, routes, logger options,
10
+ * and custom properties. Provides type-safe accessors for common configuration keys and supports
11
+ * nested property access via `get()` and `set()`.
12
+ *
13
+ * ### Usage
14
+ *
15
+ * ```typescript
16
+ * import {DIConfiguration} from "@tsed/di";
17
+ *
18
+ * const config = new DIConfiguration({
19
+ * rootDir: __dirname,
20
+ * env: Env.PROD,
21
+ * logger: {level: "info"}
22
+ * });
23
+ *
24
+ * config.set("custom.nested.key", "value");
25
+ * const value = config.get("custom.nested.key");
26
+ * ```
27
+ *
28
+ * @public
29
+ */
6
30
  export declare class DIConfiguration {
7
31
  readonly default: Map<string, any>;
8
32
  protected map: Map<string, any>;
@@ -1,3 +1,31 @@
1
1
  import { DILogger } from "../interfaces/DILogger.js";
2
+ /**
3
+ * Injection token for the DI logger service.
4
+ *
5
+ * Use this symbol to inject the configured logger instance into your services.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * ```typescript
10
+ * import {Injectable, Inject, LOGGER} from "@tsed/di";
11
+ *
12
+ * @Injectable()
13
+ * class MyService {
14
+ * @Inject(LOGGER)
15
+ * logger: LOGGER;
16
+ *
17
+ * doSomething() {
18
+ * this.logger.info("Doing something");
19
+ * }
20
+ * }
21
+ * ```
22
+ *
23
+ * @public
24
+ */
2
25
  export declare const LOGGER: unique symbol;
26
+ /**
27
+ * Type alias for the injected logger instance.
28
+ *
29
+ * @public
30
+ */
3
31
  export type LOGGER = DILogger;