@navios/core 1.1.0 → 2.0.0-alpha.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.
Files changed (237) hide show
  1. package/CHANGELOG.md +85 -13
  2. package/README.md +69 -220
  3. package/lib/async-context-BAdt7bno.d.mts +239 -0
  4. package/lib/async-context-BAdt7bno.d.mts.map +1 -0
  5. package/lib/async-context-RsWmy2Hi.d.cts +239 -0
  6. package/lib/async-context-RsWmy2Hi.d.cts.map +1 -0
  7. package/lib/attribute-factory-BW1kgBqf.d.mts +70 -0
  8. package/lib/attribute-factory-BW1kgBqf.d.mts.map +1 -0
  9. package/lib/attribute-factory-DqN4x5XM.d.cts +70 -0
  10. package/lib/attribute-factory-DqN4x5XM.d.cts.map +1 -0
  11. package/lib/attribute-value-BNiJjxl1.mjs +225 -0
  12. package/lib/attribute-value-BNiJjxl1.mjs.map +1 -0
  13. package/lib/attribute-value-Cux5HhOL.cjs +314 -0
  14. package/lib/attribute-value-Cux5HhOL.cjs.map +1 -0
  15. package/lib/basic-execution-context-5uq2DvEA.cjs +318 -0
  16. package/lib/basic-execution-context-5uq2DvEA.cjs.map +1 -0
  17. package/lib/basic-execution-context-u1VktGoM.mjs +277 -0
  18. package/lib/basic-execution-context-u1VktGoM.mjs.map +1 -0
  19. package/lib/execution-context-BVSmLkYp.d.cts +71 -0
  20. package/lib/execution-context-BVSmLkYp.d.cts.map +1 -0
  21. package/lib/execution-context-C5F9rojO.d.mts +71 -0
  22. package/lib/execution-context-C5F9rojO.d.mts.map +1 -0
  23. package/lib/execution-context-token--cKS4cJv.cjs +270 -0
  24. package/lib/execution-context-token--cKS4cJv.cjs.map +1 -0
  25. package/lib/execution-context-token-Cb3M3Ao0.mjs +223 -0
  26. package/lib/execution-context-token-Cb3M3Ao0.mjs.map +1 -0
  27. package/lib/index.cjs +1672 -4426
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +842 -3
  30. package/lib/index.d.cts.map +1 -0
  31. package/lib/index.d.mts +842 -3
  32. package/lib/index.d.mts.map +1 -0
  33. package/lib/index.mjs +1559 -4221
  34. package/lib/index.mjs.map +1 -1
  35. package/lib/legacy-compat/index.cjs +72 -371
  36. package/lib/legacy-compat/index.cjs.map +1 -1
  37. package/lib/legacy-compat/index.d.cts +42 -382
  38. package/lib/legacy-compat/index.d.cts.map +1 -1
  39. package/lib/legacy-compat/index.d.mts +41 -382
  40. package/lib/legacy-compat/index.d.mts.map +1 -1
  41. package/lib/legacy-compat/index.mjs +51 -345
  42. package/lib/legacy-compat/index.mjs.map +1 -1
  43. package/lib/module-Bz83ZnJ5.cjs +173 -0
  44. package/lib/module-Bz83ZnJ5.cjs.map +1 -0
  45. package/lib/module-options-CSqQUSTm.d.mts +51 -0
  46. package/lib/module-options-CSqQUSTm.d.mts.map +1 -0
  47. package/lib/module-options-DSRBri4J.d.cts +51 -0
  48. package/lib/module-options-DSRBri4J.d.cts.map +1 -0
  49. package/lib/module-zPXwR2qp.mjs +138 -0
  50. package/lib/module-zPXwR2qp.mjs.map +1 -0
  51. package/lib/settled-within-B6gpu2XW.cjs +32 -0
  52. package/lib/settled-within-B6gpu2XW.cjs.map +1 -0
  53. package/lib/settled-within-Bc2pj8WB.mjs +21 -0
  54. package/lib/settled-within-Bc2pj8WB.mjs.map +1 -0
  55. package/lib/testing/index.cjs +74 -414
  56. package/lib/testing/index.cjs.map +1 -1
  57. package/lib/testing/index.d.cts +25 -385
  58. package/lib/testing/index.d.cts.map +1 -1
  59. package/lib/testing/index.d.mts +24 -385
  60. package/lib/testing/index.d.mts.map +1 -1
  61. package/lib/testing/index.mjs +72 -408
  62. package/lib/testing/index.mjs.map +1 -1
  63. package/lib/transport.cjs +36 -0
  64. package/lib/transport.d.cts +254 -0
  65. package/lib/transport.d.cts.map +1 -0
  66. package/lib/transport.d.mts +254 -0
  67. package/lib/transport.d.mts.map +1 -0
  68. package/lib/transport.mjs +6 -0
  69. package/package.json +37 -17
  70. package/docs/README.md +0 -316
  71. package/docs/adapters.md +0 -308
  72. package/docs/application-setup.md +0 -524
  73. package/docs/attributes.md +0 -689
  74. package/docs/controllers.md +0 -373
  75. package/docs/endpoints.md +0 -444
  76. package/docs/exceptions.md +0 -352
  77. package/docs/guards.md +0 -550
  78. package/docs/legacy-compat.md +0 -356
  79. package/docs/modules.md +0 -377
  80. package/docs/quick-start.md +0 -290
  81. package/docs/services.md +0 -427
  82. package/docs/testing.md +0 -827
  83. package/lib/index-3LcTrbxz.d.mts +0 -3804
  84. package/lib/index-3LcTrbxz.d.mts.map +0 -1
  85. package/lib/index-B14SekVb.d.cts +0 -3804
  86. package/lib/index-B14SekVb.d.cts.map +0 -1
  87. package/lib/navios.factory-CUrO_p6K.cjs +0 -4538
  88. package/lib/navios.factory-CUrO_p6K.cjs.map +0 -1
  89. package/lib/navios.factory-DjUOOVVL.mjs +0 -4151
  90. package/lib/navios.factory-DjUOOVVL.mjs.map +0 -1
  91. package/lib/tokens-BEuBMGGX.cjs +0 -193
  92. package/lib/tokens-BEuBMGGX.cjs.map +0 -1
  93. package/lib/tokens-COyNGV1I.mjs +0 -97
  94. package/lib/tokens-COyNGV1I.mjs.map +0 -1
  95. package/lib/use-guards.decorator-DLmRl2CV.mjs +0 -336
  96. package/lib/use-guards.decorator-DLmRl2CV.mjs.map +0 -1
  97. package/lib/use-guards.decorator-DhumFTk3.cjs +0 -444
  98. package/lib/use-guards.decorator-DhumFTk3.cjs.map +0 -1
  99. package/project.json +0 -66
  100. package/src/__tests__/attribute.factory.spec.mts +0 -300
  101. package/src/__tests__/config.service.spec.mts +0 -43
  102. package/src/__tests__/console-logger.service.spec.mts +0 -312
  103. package/src/__tests__/controller-resolver.spec.mts +0 -229
  104. package/src/__tests__/controller.spec.mts +0 -58
  105. package/src/__tests__/guard-runner.service.spec.mts +0 -399
  106. package/src/__tests__/logger.service.spec.mts +0 -147
  107. package/src/__tests__/responders.spec.mts +0 -340
  108. package/src/__tests__/testing-module.spec.mts +0 -459
  109. package/src/__tests__/unit-testing-module.spec.mts +0 -424
  110. package/src/attribute.factory.mts +0 -325
  111. package/src/config/config-service.interface.mts +0 -47
  112. package/src/config/config.provider.mts +0 -69
  113. package/src/config/config.service.mts +0 -176
  114. package/src/config/index.mts +0 -5
  115. package/src/config/types.mts +0 -58
  116. package/src/config/utils/helpers.mts +0 -23
  117. package/src/config/utils/index.mts +0 -1
  118. package/src/decorators/controller.decorator.mts +0 -81
  119. package/src/decorators/endpoint.decorator.mts +0 -181
  120. package/src/decorators/header.decorator.mts +0 -38
  121. package/src/decorators/http-code.decorator.mts +0 -38
  122. package/src/decorators/index.mts +0 -8
  123. package/src/decorators/module.decorator.mts +0 -106
  124. package/src/decorators/multipart.decorator.mts +0 -169
  125. package/src/decorators/stream.decorator.mts +0 -155
  126. package/src/decorators/use-guards.decorator.mts +0 -73
  127. package/src/exceptions/bad-request.exception.mts +0 -28
  128. package/src/exceptions/conflict.exception.mts +0 -31
  129. package/src/exceptions/forbidden.exception.mts +0 -30
  130. package/src/exceptions/http.exception.mts +0 -33
  131. package/src/exceptions/index.mts +0 -7
  132. package/src/exceptions/internal-server-error.exception.mts +0 -33
  133. package/src/exceptions/not-found.exception.mts +0 -33
  134. package/src/exceptions/unauthorized.exception.mts +0 -30
  135. package/src/factories/adapter.factory.mts +0 -20
  136. package/src/factories/endpoint-adapter.factory.mts +0 -21
  137. package/src/factories/http-adapter.factory.mts +0 -20
  138. package/src/factories/index.mts +0 -8
  139. package/src/factories/multipart-adapter.factory.mts +0 -21
  140. package/src/factories/reply.factory.mts +0 -21
  141. package/src/factories/request.factory.mts +0 -21
  142. package/src/factories/stream-adapter.factory.mts +0 -20
  143. package/src/factories/xml-stream-adapter.factory.mts +0 -20
  144. package/src/index.mts +0 -16
  145. package/src/interfaces/abstract-adapter.interface.mts +0 -32
  146. package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
  147. package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
  148. package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
  149. package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
  150. package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
  151. package/src/interfaces/adapter-environment.interface.mts +0 -74
  152. package/src/interfaces/can-activate.mts +0 -38
  153. package/src/interfaces/http-header.mts +0 -18
  154. package/src/interfaces/index.mts +0 -14
  155. package/src/interfaces/navios-module.mts +0 -28
  156. package/src/interfaces/plugin-context.mts +0 -104
  157. package/src/interfaces/plugin-stage.mts +0 -62
  158. package/src/interfaces/plugin.interface.mts +0 -119
  159. package/src/interfaces/staged-plugin.interface.mts +0 -209
  160. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
  161. package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
  162. package/src/legacy-compat/attribute.factory.mts +0 -351
  163. package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
  164. package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
  165. package/src/legacy-compat/decorators/header.decorator.mts +0 -43
  166. package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
  167. package/src/legacy-compat/decorators/index.mts +0 -11
  168. package/src/legacy-compat/decorators/module.decorator.mts +0 -37
  169. package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
  170. package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
  171. package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
  172. package/src/legacy-compat/index.mts +0 -57
  173. package/src/logger/README.md +0 -3
  174. package/src/logger/console-logger.service.mts +0 -714
  175. package/src/logger/index.mts +0 -6
  176. package/src/logger/log-levels.mts +0 -21
  177. package/src/logger/logger-service.interface.mts +0 -42
  178. package/src/logger/logger.service.mts +0 -113
  179. package/src/logger/logger.tokens.mts +0 -44
  180. package/src/logger/utils/cli-colors.util.mts +0 -17
  181. package/src/logger/utils/filter-log-levelts.util.mts +0 -29
  182. package/src/logger/utils/index.mts +0 -5
  183. package/src/logger/utils/is-log-level-enabled.mts +0 -33
  184. package/src/logger/utils/is-log-level.util.mts +0 -10
  185. package/src/logger/utils/shared.utils.mts +0 -51
  186. package/src/metadata/controller.metadata.mts +0 -79
  187. package/src/metadata/handler.metadata.mts +0 -80
  188. package/src/metadata/index.mts +0 -4
  189. package/src/metadata/module.metadata.mts +0 -116
  190. package/src/metadata/navios-managed.metadata.mts +0 -42
  191. package/src/navios.application.mts +0 -678
  192. package/src/navios.environment.mts +0 -42
  193. package/src/navios.factory.mts +0 -158
  194. package/src/responders/enums/framework-error.enum.mts +0 -38
  195. package/src/responders/enums/index.mts +0 -1
  196. package/src/responders/index.mts +0 -4
  197. package/src/responders/interfaces/error-responder.interface.mts +0 -42
  198. package/src/responders/interfaces/error-response.interface.mts +0 -22
  199. package/src/responders/interfaces/index.mts +0 -3
  200. package/src/responders/interfaces/problem-details.interface.mts +0 -34
  201. package/src/responders/services/error-response-producer.service.mts +0 -143
  202. package/src/responders/services/forbidden-responder.service.mts +0 -77
  203. package/src/responders/services/index.mts +0 -5
  204. package/src/responders/services/internal-server-error-responder.service.mts +0 -57
  205. package/src/responders/services/not-found-responder.service.mts +0 -76
  206. package/src/responders/services/validation-error-responder.service.mts +0 -78
  207. package/src/responders/tokens/index.mts +0 -1
  208. package/src/responders/tokens/responder.tokens.mts +0 -84
  209. package/src/services/abstract-handler-adapter.service.mts +0 -366
  210. package/src/services/guard-runner.service.mts +0 -152
  211. package/src/services/index.mts +0 -4
  212. package/src/services/instance-resolver.service.mts +0 -177
  213. package/src/services/module-loader.service.mts +0 -255
  214. package/src/stores/index.mts +0 -1
  215. package/src/stores/request-id.store.mts +0 -85
  216. package/src/testing/index.mts +0 -3
  217. package/src/testing/testing-module.mts +0 -393
  218. package/src/testing/unit-testing-module.mts +0 -298
  219. package/src/tokens/adapter.token.mts +0 -6
  220. package/src/tokens/endpoint-adapter.token.mts +0 -8
  221. package/src/tokens/execution-context.token.mts +0 -9
  222. package/src/tokens/http-adapter.token.mts +0 -8
  223. package/src/tokens/index.mts +0 -10
  224. package/src/tokens/multipart-adapter.token.mts +0 -8
  225. package/src/tokens/navios-options.token.mts +0 -6
  226. package/src/tokens/reply.token.mts +0 -3
  227. package/src/tokens/request.token.mts +0 -3
  228. package/src/tokens/stream-adapter.token.mts +0 -8
  229. package/src/tokens/xml-stream-adapter.token.mts +0 -8
  230. package/src/utils/adapter-supports.util.mts +0 -47
  231. package/src/utils/define-plugin.mts +0 -251
  232. package/src/utils/index.mts +0 -2
  233. package/tsconfig.json +0 -21
  234. package/tsconfig.lib.json +0 -8
  235. package/tsconfig.spec.json +0 -15
  236. package/tsdown.config.mts +0 -35
  237. package/vitest.config.mts +0 -15
@@ -1,42 +0,0 @@
1
- import type { ClassType } from '@navios/di'
2
-
3
- /**
4
- * Symbol used to identify Navios-managed classes (Controller, Module, MessageController, etc.).
5
- * This allows AttributeFactory to work with any Navios-managed class type generically.
6
- */
7
- export const NaviosManagedMetadataKey = Symbol('NaviosManagedMetadataKey')
8
-
9
- /**
10
- * Interface for metadata that has custom attributes.
11
- * Used by Navios-managed classes (Controller, Module, MessageController, etc.).
12
- */
13
- export interface ManagedMetadata {
14
- customAttributes: Map<string | symbol, any>
15
- }
16
-
17
- /**
18
- * Gets managed metadata from a class if it exists.
19
- * This is a generic function that works with any Navios-managed class type.
20
- *
21
- * @param target - The class to check
22
- * @returns The metadata with customAttributes, or null if not managed
23
- */
24
- export function getManagedMetadata(target: ClassType): ManagedMetadata | null {
25
- // @ts-expect-error - Checking for managed metadata key
26
- if (target[NaviosManagedMetadataKey]) {
27
- // @ts-expect-error - Accessing managed metadata
28
- return target[NaviosManagedMetadataKey] as ManagedMetadata
29
- }
30
- return null
31
- }
32
-
33
- /**
34
- * Checks if a class is Navios-managed (has managed metadata).
35
- *
36
- * @param target - The class to check
37
- * @returns true if the class is Navios-managed
38
- */
39
- export function hasManagedMetadata(target: ClassType): boolean {
40
- return getManagedMetadata(target) !== null
41
- }
42
-
@@ -1,678 +0,0 @@
1
- import type {
2
- ClassType,
3
- ClassTypeWithArgument,
4
- ClassTypeWithInstance,
5
- InjectionTokenSchemaType,
6
- Registry,
7
- } from '@navios/di'
8
- import type { z } from 'zod/v4'
9
-
10
- import {
11
- BoundInjectionToken,
12
- Container,
13
- FactoryInjectionToken,
14
- inject,
15
- Injectable,
16
- InjectionToken,
17
- } from '@navios/di'
18
-
19
- import type {
20
- AbstractAdapterInterface,
21
- AdapterEnvironment,
22
- AnyPluginDefinition,
23
- ContainerOnlyContext,
24
- DefaultAdapterEnvironment,
25
- FullPluginContext,
26
- HttpAdapterEnvironment,
27
- ModulesLoadedContext,
28
- NaviosModule,
29
- PluginStage,
30
- } from './interfaces/index.mjs'
31
- import type { LoggerService, LogLevel } from './logger/index.mjs'
32
- import type { NaviosEnvironmentOptions } from './navios.environment.mjs'
33
-
34
- import {
35
- PLUGIN_STAGES_ORDER,
36
- PluginStageBase,
37
- PluginStages,
38
- postStage,
39
- preStage,
40
- } from './interfaces/index.mjs'
41
- import { Logger } from './logger/index.mjs'
42
- import { NaviosEnvironment } from './navios.environment.mjs'
43
- import { ModuleLoaderService } from './services/index.mjs'
44
- import { AdapterToken } from './tokens/index.mjs'
45
- import { assertAdapterSupports } from './utils/index.mjs'
46
-
47
- /**
48
- * Options for configuring the Navios application context.
49
- * These options control the application configuration.
50
- */
51
- export interface NaviosApplicationOptions {
52
- /**
53
- * Specifies the logger to use. Pass `false` to turn off logging.
54
- *
55
- * - `LoggerService` instance: Use a custom logger implementation
56
- * - `LogLevel[]`: Enable specific log levels (e.g., ['error', 'warn', 'log'])
57
- * - `false`: Disable logging completely
58
- */
59
- logger?: LoggerService | LogLevel[] | false
60
-
61
- /**
62
- * Specifies a custom registry to use. Useful for testing.
63
- * If not provided, a new Registry will be created.
64
- */
65
- registry?: Registry
66
-
67
- /**
68
- * Specifies a custom container to use. Useful for testing.
69
- * If not provided, a new Container will be created.
70
- */
71
- container?: Container
72
-
73
- /**
74
- * Adapter environment(s) to use for the application.
75
- * Can be a single adapter or an array of adapters.
76
- *
77
- * @example
78
- * ```typescript
79
- * adapter: defineFastifyEnvironment()
80
- * // or
81
- * adapter: [defineFastifyEnvironment()]
82
- * ```
83
- */
84
- adapter: NaviosEnvironmentOptions | NaviosEnvironmentOptions[]
85
-
86
- /**
87
- * Whether to validate response schemas.
88
- * When `false`, response schema validation is skipped for better performance.
89
- * @default true
90
- */
91
- validateResponses?: boolean
92
-
93
- /**
94
- * Whether to enable request ID propagation via AsyncLocalStorage.
95
- * When `true`, request IDs are available via `getRequestId()` throughout the request.
96
- * @default false
97
- */
98
- enableRequestId?: boolean
99
- }
100
-
101
- /**
102
- * Main application class for Navios.
103
- *
104
- * This class represents a Navios application instance and provides methods
105
- * for initializing, configuring, and managing the application lifecycle.
106
- *
107
- * @example
108
- * ```typescript
109
- * const app = await NaviosFactory.create(AppModule, {
110
- * adapter: defineFastifyEnvironment(),
111
- * })
112
- *
113
- * app.setGlobalPrefix('/api')
114
- * app.enableCors({ origin: ['http://localhost:3000'] })
115
- * await app.init()
116
- * await app.listen({ port: 3000, host: '0.0.0.0' })
117
- * ```
118
- */
119
- @Injectable()
120
- export class NaviosApplication<
121
- Environment extends AdapterEnvironment = DefaultAdapterEnvironment,
122
- > {
123
- private environment = inject(NaviosEnvironment)
124
- private moduleLoader = inject(ModuleLoaderService)
125
- private adapter: Environment['adapter'] | null = null
126
- private logger = inject(Logger, {
127
- context: NaviosApplication.name,
128
- })
129
- protected container = inject(Container)
130
-
131
- private appModule: ClassTypeWithInstance<NaviosModule> | null = null
132
- private options: NaviosApplicationOptions = {
133
- adapter: [],
134
- }
135
-
136
- /**
137
- * Plugin storage organized by stage for efficient execution.
138
- * Each stage has a Set of plugin definitions.
139
- */
140
- private plugins: Map<PluginStage, Set<AnyPluginDefinition>> = new Map(
141
- PLUGIN_STAGES_ORDER.map((stage) => [stage, new Set()]),
142
- )
143
-
144
- /**
145
- * Queue of adapter configuration methods to apply after adapter resolution.
146
- * Allows calling methods like enableCors() before init().
147
- */
148
- private pendingAdapterCalls: Array<{
149
- method: string
150
- args: unknown[]
151
- }> = []
152
-
153
- /**
154
- * Indicates whether the application has been initialized.
155
- * Set to `true` after `init()` completes successfully.
156
- */
157
- isInitialized = false
158
-
159
- /**
160
- * Sets up the application with the provided module and options.
161
- * This is called automatically by NaviosFactory.create().
162
- *
163
- * Note: Adapter resolution has been moved to init() to allow
164
- * plugins to modify the container/registry before adapter instantiation.
165
- *
166
- * @param appModule - The root application module
167
- * @param options - Application configuration options
168
- * @internal
169
- */
170
- async setup(
171
- appModule: ClassTypeWithInstance<NaviosModule>,
172
- options: NaviosApplicationOptions = {
173
- adapter: [],
174
- },
175
- ) {
176
- this.appModule = appModule
177
- this.options = options
178
- // Note: Adapter resolution moved to init() for plugin hooks
179
- }
180
-
181
- /**
182
- * Gets the dependency injection container used by this application.
183
- *
184
- * @returns The Container instance
185
- */
186
- getContainer() {
187
- return this.container
188
- }
189
-
190
- /**
191
- * Returns the current adapter instance.
192
- *
193
- * @returns The adapter instance
194
- * @throws Error if adapter is not initialized
195
- */
196
- getAdapter(): Environment['adapter'] {
197
- if (!this.adapter) {
198
- throw new Error('Adapter not initialized')
199
- }
200
- return this.adapter
201
- }
202
-
203
- /**
204
- * Registers one or more plugins for initialization during the application lifecycle.
205
- *
206
- * Plugins can target specific stages or use the legacy interface (defaults to post:modules-init).
207
- * Plugins are executed in stage order, and within a stage in registration order.
208
- *
209
- * @param definitions - Single plugin definition or array of definitions
210
- * @returns this for method chaining
211
- *
212
- * @example
213
- * ```typescript
214
- * // Single plugin (legacy or staged)
215
- * app.usePlugin(defineOpenApiPlugin({ info: { title: 'My API', version: '1.0.0' } }))
216
- *
217
- * // Multiple plugins in one call
218
- * app.usePlugin([
219
- * defineOtelPlugin({ serviceName: 'my-service' }),
220
- * defineOpenApiPlugin({ info: { title: 'My API', version: '1.0.0' } }),
221
- * ])
222
- *
223
- * // Staged plugin with explicit stage
224
- * app.usePlugin(definePreAdapterResolvePlugin({
225
- * name: 'early-setup',
226
- * register: (ctx) => { ... },
227
- * })({}))
228
- * ```
229
- */
230
- usePlugin<TOptions, TAdapter extends AbstractAdapterInterface>(
231
- definitions:
232
- | AnyPluginDefinition<TOptions, TAdapter>
233
- | AnyPluginDefinition<TOptions, TAdapter>[],
234
- ): this {
235
- const definitionsArray = Array.isArray(definitions)
236
- ? definitions
237
- : [definitions]
238
-
239
- for (const definition of definitionsArray) {
240
- const stage = this.resolvePluginStage(definition)
241
- const stageSet = this.plugins.get(stage)
242
-
243
- if (!stageSet) {
244
- throw new Error(`Unknown plugin stage: ${stage}`)
245
- }
246
-
247
- stageSet.add(definition as AnyPluginDefinition)
248
- this.logger.debug(
249
- `Registered plugin "${definition.plugin.name}" for stage: ${stage}`,
250
- )
251
- }
252
-
253
- return this
254
- }
255
-
256
- /**
257
- * Resolves the stage for a plugin definition.
258
- * Staged plugins use their explicit stage, legacy plugins default to post:modules-init.
259
- */
260
- private resolvePluginStage(definition: AnyPluginDefinition): PluginStage {
261
- if ('stage' in definition.plugin) {
262
- return definition.plugin.stage
263
- }
264
- // Legacy plugins default to post:modules-init for backward compatibility
265
- return PluginStages.POST_MODULES_INIT
266
- }
267
-
268
- /**
269
- * Initializes the application.
270
- *
271
- * This method executes the following lifecycle stages:
272
- * 1. pre:modules-traverse → Load modules → post:modules-traverse
273
- * 2. pre:adapter-resolve → Resolve adapter → post:adapter-resolve
274
- * 3. pre:adapter-setup → Setup adapter → post:adapter-setup
275
- * 4. pre:modules-init → Initialize modules → post:modules-init
276
- * 5. pre:ready → Ready signal → post:ready
277
- *
278
- * Must be called before `listen()`.
279
- *
280
- * @throws Error if app module is not set
281
- *
282
- * @example
283
- * ```typescript
284
- * const app = await NaviosFactory.create(AppModule, {
285
- * adapter: defineFastifyEnvironment(),
286
- * })
287
- * await app.init()
288
- * await app.listen({ port: 3000 })
289
- * ```
290
- */
291
- async init() {
292
- if (!this.appModule) {
293
- throw new Error('App module is not set. Call setAppModule() first.')
294
- }
295
-
296
- // Stage 1: Load modules
297
- await this.wrapStage(PluginStageBase.MODULES_TRAVERSE, () =>
298
- this.moduleLoader.loadModules(this.appModule!),
299
- )
300
-
301
- // Stage 2: Resolve adapter (moved from setup())
302
- // Note: If no adapter configured, adapter stages are silently skipped
303
- if (this.environment.hasAdapterSetup()) {
304
- await this.wrapStage(PluginStageBase.ADAPTER_RESOLVE, async () => {
305
- this.adapter = (await this.container.get(
306
- AdapterToken,
307
- )) as Environment['adapter']
308
- // Apply any configuration calls that were queued before adapter resolution
309
- this.applyPendingAdapterCalls()
310
- })
311
-
312
- // Stage 3: Setup adapter
313
- if (this.adapter) {
314
- await this.wrapStage(PluginStageBase.ADAPTER_SETUP, () =>
315
- this.adapter!.setupAdapter(this.options),
316
- )
317
- }
318
- }
319
-
320
- // Stage 4: Initialize modules (always runs)
321
- await this.wrapStage(PluginStageBase.MODULES_INIT, () => this.initModules())
322
-
323
- // Stage 5: Ready signal
324
- if (this.adapter) {
325
- await this.wrapStage(PluginStageBase.READY, () => this.adapter!.ready())
326
- }
327
-
328
- this.isInitialized = true
329
- this.logger.debug('Navios application initialized')
330
- }
331
-
332
- /**
333
- * Wraps an operation with pre/post plugin stage execution.
334
- *
335
- * @param baseName - The base stage name (e.g., 'modules-traverse')
336
- * @param operation - The operation to execute between pre/post stages
337
- */
338
- private async wrapStage<T>(
339
- baseName: PluginStageBase,
340
- operation: () => Promise<T> | T,
341
- ): Promise<T> {
342
- await this.executePluginStage(preStage(baseName))
343
- const result = await operation()
344
- await this.executePluginStage(postStage(baseName))
345
- return result
346
- }
347
-
348
- /**
349
- * Executes all plugins registered for a specific stage.
350
- *
351
- * @param stage - The lifecycle stage to execute plugins for
352
- */
353
- private async executePluginStage(stage: PluginStage): Promise<void> {
354
- const stagePlugins = this.plugins.get(stage)
355
-
356
- if (!stagePlugins || stagePlugins.size === 0) {
357
- return
358
- }
359
-
360
- const context = this.buildContextForStage(stage)
361
-
362
- this.logger.debug(
363
- `Executing ${stagePlugins.size} plugin(s) for stage: ${stage}`,
364
- )
365
-
366
- for (const { plugin, options } of stagePlugins) {
367
- this.logger.debug(`Executing plugin: ${plugin.name} (stage: ${stage})`)
368
-
369
- try {
370
- await plugin.register(context as never, options)
371
- } catch (error) {
372
- this.logger.error(
373
- `Plugin "${plugin.name}" failed at stage "${stage}"`,
374
- error,
375
- )
376
- throw error
377
- }
378
- }
379
- }
380
-
381
- /**
382
- * Builds the appropriate context object for a given stage.
383
- *
384
- * @param stage - The lifecycle stage
385
- * @returns Context object with stage-appropriate properties
386
- */
387
- private buildContextForStage(
388
- stage: PluginStage,
389
- ): ContainerOnlyContext | ModulesLoadedContext | FullPluginContext {
390
- const baseContext: ContainerOnlyContext = {
391
- container: this.container,
392
- }
393
-
394
- if (stage === PluginStages.PRE_MODULES_TRAVERSE) {
395
- return baseContext
396
- }
397
-
398
- const modulesContext: ModulesLoadedContext = {
399
- ...baseContext,
400
- modules: this.moduleLoader.getAllModules(),
401
- moduleLoader: this.moduleLoader,
402
- }
403
-
404
- const isPreAdapterStage =
405
- stage === PluginStages.POST_MODULES_TRAVERSE ||
406
- stage === PluginStages.PRE_ADAPTER_RESOLVE
407
-
408
- if (isPreAdapterStage) {
409
- return modulesContext
410
- }
411
-
412
- if (!this.adapter) {
413
- throw new Error(`Cannot execute stage "${stage}" without adapter`)
414
- }
415
-
416
- return {
417
- ...modulesContext,
418
- adapter: this.adapter,
419
- } as FullPluginContext
420
- }
421
-
422
- private async initModules() {
423
- const modules = this.moduleLoader.getAllModules()
424
- if (this.adapter) {
425
- await this.adapter.onModulesInit(modules)
426
- }
427
- }
428
-
429
- /**
430
- * Applies any pending adapter configuration calls that were queued
431
- * before the adapter was resolved.
432
- */
433
- private applyPendingAdapterCalls(): void {
434
- if (!this.adapter || this.pendingAdapterCalls.length === 0) {
435
- return
436
- }
437
-
438
- for (const { method, args } of this.pendingAdapterCalls) {
439
- assertAdapterSupports(
440
- this.adapter,
441
- method as keyof AbstractAdapterInterface,
442
- )
443
- ;(this.adapter as Record<string, (...args: unknown[]) => unknown>)[method](
444
- ...args,
445
- )
446
- }
447
-
448
- // Clear the queue after applying
449
- this.pendingAdapterCalls = []
450
- }
451
-
452
- /**
453
- * Gets a service instance from the dependency injection container.
454
- *
455
- * This is a shorthand for `app.getContainer().get(token)`.
456
- *
457
- * @param token - The injection token or class to resolve
458
- * @returns Promise resolving to the service instance
459
- *
460
- * @example
461
- * ```typescript
462
- * const userService = await app.get(UserService)
463
- * const config = await app.get(ConfigToken)
464
- * ```
465
- */
466
- get<T extends ClassType>(token: T): Promise<InstanceType<T>>
467
- get<T extends ClassTypeWithArgument<R>, R>(
468
- token: T,
469
- args: R,
470
- ): Promise<InstanceType<T>>
471
- get<T, S extends InjectionTokenSchemaType>(
472
- token: InjectionToken<T, S>,
473
- args: z.input<S>,
474
- ): Promise<T>
475
- get<T, S extends InjectionTokenSchemaType, R extends boolean>(
476
- token: InjectionToken<T, S, R>,
477
- ): Promise<T>
478
- get<T>(token: InjectionToken<T, undefined>): Promise<T>
479
- get<T>(token: BoundInjectionToken<T, any>): Promise<T>
480
- get<T>(token: FactoryInjectionToken<T, any>): Promise<T>
481
- async get(
482
- token:
483
- | ClassType
484
- | InjectionToken<any>
485
- | BoundInjectionToken<any, any>
486
- | FactoryInjectionToken<any, any>,
487
- args?: unknown,
488
- ): Promise<any> {
489
- return this.container.get(token as any, args)
490
- }
491
-
492
- /**
493
- * Configures the adapter with additional options before initialization.
494
- *
495
- * This method allows setting adapter-specific configuration options
496
- * before the adapter is initialized. Must be called before `init()`.
497
- *
498
- * @param options - Adapter-specific configuration options
499
- * @returns this for method chaining
500
- * @throws Error if called after init() or if adapter doesn't support configure
501
- *
502
- * @example
503
- * ```typescript
504
- * // With Fastify adapter
505
- * app.configure({ trustProxy: true, logger: true })
506
- *
507
- * // With Bun adapter
508
- * app.configure({ development: true })
509
- * ```
510
- */
511
- configure(options: Partial<Environment['options']>): this {
512
- if (this.isInitialized) {
513
- throw new Error('configure() must be called before init()')
514
- }
515
- if (this.adapter) {
516
- assertAdapterSupports(this.adapter, 'configure')
517
- this.adapter.configure(options)
518
- } else {
519
- this.pendingAdapterCalls.push({ method: 'configure', args: [options] })
520
- }
521
- return this
522
- }
523
-
524
- /**
525
- * Enables CORS (Cross-Origin Resource Sharing) for the application.
526
- *
527
- * @param options - CORS configuration options (adapter-specific)
528
- * @throws Error if adapter doesn't support enableCors
529
- *
530
- * @example
531
- * ```typescript
532
- * app.enableCors({
533
- * origin: ['http://localhost:3000', 'https://example.com'],
534
- * methods: ['GET', 'POST', 'PUT', 'DELETE'],
535
- * credentials: true,
536
- * })
537
- * ```
538
- */
539
- enableCors(
540
- options: Environment extends HttpAdapterEnvironment
541
- ? Environment['corsOptions']
542
- : never,
543
- ): void {
544
- if (this.adapter) {
545
- assertAdapterSupports(this.adapter, 'enableCors')
546
- this.adapter.enableCors(options)
547
- } else {
548
- this.pendingAdapterCalls.push({ method: 'enableCors', args: [options] })
549
- }
550
- }
551
-
552
- /**
553
- * Enables multipart/form-data support for file uploads.
554
- *
555
- * @param options - Multipart configuration options (adapter-specific)
556
- * @throws Error if adapter doesn't support enableMultipart
557
- *
558
- * @example
559
- * ```typescript
560
- * app.enableMultipart({
561
- * limits: {
562
- * fileSize: 1024 * 1024 * 10, // 10MB
563
- * },
564
- * })
565
- * ```
566
- */
567
- enableMultipart(
568
- options: Environment extends HttpAdapterEnvironment
569
- ? Environment['multipartOptions']
570
- : never,
571
- ): void {
572
- if (this.adapter) {
573
- assertAdapterSupports(this.adapter, 'enableMultipart')
574
- this.adapter.enableMultipart(options)
575
- } else {
576
- this.pendingAdapterCalls.push({ method: 'enableMultipart', args: [options] })
577
- }
578
- }
579
-
580
- /**
581
- * Sets a global prefix for all routes.
582
- *
583
- * @param prefix - The prefix to prepend to all route URLs (e.g., '/api')
584
- * @throws Error if adapter doesn't support setGlobalPrefix
585
- *
586
- * @example
587
- * ```typescript
588
- * app.setGlobalPrefix('/api/v1')
589
- * // All routes will be prefixed with /api/v1
590
- * ```
591
- */
592
- setGlobalPrefix(prefix: string): void {
593
- if (this.adapter) {
594
- assertAdapterSupports(this.adapter, 'setGlobalPrefix')
595
- this.adapter.setGlobalPrefix(prefix)
596
- } else {
597
- this.pendingAdapterCalls.push({ method: 'setGlobalPrefix', args: [prefix] })
598
- }
599
- }
600
-
601
- /**
602
- * Gets the underlying HTTP server instance.
603
- *
604
- * The type of the returned server depends on the adapter used:
605
- * - Fastify adapter: Returns FastifyInstance
606
- * - Bun adapter: Returns Bun.Server
607
- *
608
- * @returns The HTTP server instance
609
- * @throws Error if adapter doesn't support getServer
610
- *
611
- * @example
612
- * ```typescript
613
- * const server = app.getServer()
614
- * // Use adapter-specific server methods
615
- * ```
616
- */
617
- getServer(): Environment extends HttpAdapterEnvironment
618
- ? Environment['server']
619
- : never {
620
- assertAdapterSupports(this.adapter, 'getServer')
621
- return this.adapter.getServer() as Environment extends HttpAdapterEnvironment
622
- ? Environment['server']
623
- : never
624
- }
625
-
626
- /**
627
- * Starts the HTTP server and begins listening for requests.
628
- *
629
- * @param options - Listen options (port, host, etc.)
630
- * @throws Error if adapter doesn't support listen
631
- *
632
- * @example
633
- * ```typescript
634
- * await app.listen({ port: 3000, host: '0.0.0.0' })
635
- * ```
636
- */
637
- async listen(
638
- options: Environment extends HttpAdapterEnvironment
639
- ? Environment['listenOptions']
640
- : never,
641
- ): Promise<string> {
642
- assertAdapterSupports(this.adapter, 'listen')
643
- return this.adapter.listen(options) as Promise<string>
644
- }
645
-
646
- /**
647
- * Disposes of application resources.
648
- *
649
- * Cleans up the adapter and module loader.
650
- * This method is called automatically by `close()`.
651
- */
652
- async dispose() {
653
- if (this.adapter) {
654
- await this.adapter.dispose()
655
- }
656
- if (this.moduleLoader) {
657
- this.moduleLoader.dispose()
658
- }
659
- }
660
-
661
- /**
662
- * Closes the application and cleans up all resources.
663
- *
664
- * This is an alias for `dispose()`.
665
- *
666
- * @example
667
- * ```typescript
668
- * // Graceful shutdown
669
- * process.on('SIGTERM', async () => {
670
- * await app.close()
671
- * process.exit(0)
672
- * })
673
- * ```
674
- */
675
- async close() {
676
- await this.dispose()
677
- }
678
- }