@navios/core 1.0.0 → 2.0.0-alpha.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 (237) hide show
  1. package/CHANGELOG.md +97 -11
  2. package/README.md +67 -220
  3. package/lib/async-context-6pdlnNLA.d.mts +237 -0
  4. package/lib/async-context-6pdlnNLA.d.mts.map +1 -0
  5. package/lib/async-context-Dqk7pE-D.d.cts +237 -0
  6. package/lib/async-context-Dqk7pE-D.d.cts.map +1 -0
  7. package/lib/attribute-factory-B3VuYnp7.d.cts +70 -0
  8. package/lib/attribute-factory-B3VuYnp7.d.cts.map +1 -0
  9. package/lib/attribute-factory-mKOXoVnV.d.mts +70 -0
  10. package/lib/attribute-factory-mKOXoVnV.d.mts.map +1 -0
  11. package/lib/attribute-value-CjX9ZkLq.cjs +172 -0
  12. package/lib/attribute-value-CjX9ZkLq.cjs.map +1 -0
  13. package/lib/attribute-value-DMEA255r.mjs +119 -0
  14. package/lib/attribute-value-DMEA255r.mjs.map +1 -0
  15. package/lib/basic-execution-context-CeGuhMOz.mjs +246 -0
  16. package/lib/basic-execution-context-CeGuhMOz.mjs.map +1 -0
  17. package/lib/basic-execution-context-DSk5MNtc.cjs +281 -0
  18. package/lib/basic-execution-context-DSk5MNtc.cjs.map +1 -0
  19. package/lib/execution-context-BPD3FeFb.d.mts +71 -0
  20. package/lib/execution-context-BPD3FeFb.d.mts.map +1 -0
  21. package/lib/execution-context-BTJdHhbf.d.cts +71 -0
  22. package/lib/execution-context-BTJdHhbf.d.cts.map +1 -0
  23. package/lib/execution-context-token-BXUKB2hf.cjs +112 -0
  24. package/lib/execution-context-token-BXUKB2hf.cjs.map +1 -0
  25. package/lib/execution-context-token-CrXmTvk2.mjs +77 -0
  26. package/lib/execution-context-token-CrXmTvk2.mjs.map +1 -0
  27. package/lib/index.cjs +1687 -4409
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +838 -3
  30. package/lib/index.d.cts.map +1 -0
  31. package/lib/index.d.mts +838 -3
  32. package/lib/index.d.mts.map +1 -0
  33. package/lib/index.mjs +1573 -4219
  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-Bha7GER_.mjs +135 -0
  44. package/lib/module-Bha7GER_.mjs.map +1 -0
  45. package/lib/module-DZewk_2r.cjs +164 -0
  46. package/lib/module-DZewk_2r.cjs.map +1 -0
  47. package/lib/module-graph-DCP9MHG0.cjs +147 -0
  48. package/lib/module-graph-DCP9MHG0.cjs.map +1 -0
  49. package/lib/module-graph-xvVEykFM.mjs +142 -0
  50. package/lib/module-graph-xvVEykFM.mjs.map +1 -0
  51. package/lib/module-metadata-C8S92seK.cjs +95 -0
  52. package/lib/module-metadata-C8S92seK.cjs.map +1 -0
  53. package/lib/module-metadata-k3RTt20x.mjs +66 -0
  54. package/lib/module-metadata-k3RTt20x.mjs.map +1 -0
  55. package/lib/module-options-Dmse0gii.d.mts +51 -0
  56. package/lib/module-options-Dmse0gii.d.mts.map +1 -0
  57. package/lib/module-options-IuDO-p8u.d.cts +51 -0
  58. package/lib/module-options-IuDO-p8u.d.cts.map +1 -0
  59. package/lib/testing/index.cjs +96 -414
  60. package/lib/testing/index.cjs.map +1 -1
  61. package/lib/testing/index.d.cts +25 -385
  62. package/lib/testing/index.d.cts.map +1 -1
  63. package/lib/testing/index.d.mts +24 -385
  64. package/lib/testing/index.d.mts.map +1 -1
  65. package/lib/testing/index.mjs +94 -408
  66. package/lib/testing/index.mjs.map +1 -1
  67. package/lib/transport.cjs +25 -0
  68. package/lib/transport.d.cts +190 -0
  69. package/lib/transport.d.cts.map +1 -0
  70. package/lib/transport.d.mts +190 -0
  71. package/lib/transport.d.mts.map +1 -0
  72. package/lib/transport.mjs +7 -0
  73. package/package.json +37 -17
  74. package/docs/README.md +0 -316
  75. package/docs/adapters.md +0 -308
  76. package/docs/application-setup.md +0 -524
  77. package/docs/attributes.md +0 -689
  78. package/docs/controllers.md +0 -373
  79. package/docs/endpoints.md +0 -444
  80. package/docs/exceptions.md +0 -352
  81. package/docs/guards.md +0 -550
  82. package/docs/legacy-compat.md +0 -356
  83. package/docs/modules.md +0 -377
  84. package/docs/quick-start.md +0 -290
  85. package/docs/services.md +0 -427
  86. package/docs/testing.md +0 -827
  87. package/lib/index-C0Sg16Eb.d.cts +0 -3365
  88. package/lib/index-C0Sg16Eb.d.cts.map +0 -1
  89. package/lib/index-DySQ6Dpd.d.mts +0 -3365
  90. package/lib/index-DySQ6Dpd.d.mts.map +0 -1
  91. package/lib/navios.factory-CO5MB_OK.cjs +0 -4125
  92. package/lib/navios.factory-CO5MB_OK.cjs.map +0 -1
  93. package/lib/navios.factory-D6Y94P9B.mjs +0 -3828
  94. package/lib/navios.factory-D6Y94P9B.mjs.map +0 -1
  95. package/lib/tokens-4J9sredA.mjs +0 -100
  96. package/lib/tokens-4J9sredA.mjs.map +0 -1
  97. package/lib/tokens-CWw9kyeD.cjs +0 -196
  98. package/lib/tokens-CWw9kyeD.cjs.map +0 -1
  99. package/lib/use-guards.decorator-BecoQSmE.mjs +0 -339
  100. package/lib/use-guards.decorator-BecoQSmE.mjs.map +0 -1
  101. package/lib/use-guards.decorator-C4ml9XaT.cjs +0 -447
  102. package/lib/use-guards.decorator-C4ml9XaT.cjs.map +0 -1
  103. package/project.json +0 -66
  104. package/src/__tests__/attribute.factory.spec.mts +0 -300
  105. package/src/__tests__/config.service.spec.mts +0 -43
  106. package/src/__tests__/console-logger.service.spec.mts +0 -312
  107. package/src/__tests__/controller-resolver.spec.mts +0 -229
  108. package/src/__tests__/controller.spec.mts +0 -58
  109. package/src/__tests__/guard-runner.service.spec.mts +0 -399
  110. package/src/__tests__/logger.service.spec.mts +0 -147
  111. package/src/__tests__/responders.spec.mts +0 -340
  112. package/src/__tests__/testing-module.spec.mts +0 -459
  113. package/src/__tests__/unit-testing-module.spec.mts +0 -424
  114. package/src/attribute.factory.mts +0 -325
  115. package/src/config/config-service.interface.mts +0 -47
  116. package/src/config/config.provider.mts +0 -69
  117. package/src/config/config.service.mts +0 -176
  118. package/src/config/index.mts +0 -5
  119. package/src/config/types.mts +0 -58
  120. package/src/config/utils/helpers.mts +0 -23
  121. package/src/config/utils/index.mts +0 -1
  122. package/src/decorators/controller.decorator.mts +0 -81
  123. package/src/decorators/endpoint.decorator.mts +0 -181
  124. package/src/decorators/header.decorator.mts +0 -38
  125. package/src/decorators/http-code.decorator.mts +0 -38
  126. package/src/decorators/index.mts +0 -8
  127. package/src/decorators/module.decorator.mts +0 -106
  128. package/src/decorators/multipart.decorator.mts +0 -169
  129. package/src/decorators/stream.decorator.mts +0 -155
  130. package/src/decorators/use-guards.decorator.mts +0 -73
  131. package/src/exceptions/bad-request.exception.mts +0 -28
  132. package/src/exceptions/conflict.exception.mts +0 -31
  133. package/src/exceptions/forbidden.exception.mts +0 -30
  134. package/src/exceptions/http.exception.mts +0 -33
  135. package/src/exceptions/index.mts +0 -7
  136. package/src/exceptions/internal-server-error.exception.mts +0 -33
  137. package/src/exceptions/not-found.exception.mts +0 -33
  138. package/src/exceptions/unauthorized.exception.mts +0 -30
  139. package/src/factories/adapter.factory.mts +0 -20
  140. package/src/factories/endpoint-adapter.factory.mts +0 -21
  141. package/src/factories/http-adapter.factory.mts +0 -20
  142. package/src/factories/index.mts +0 -8
  143. package/src/factories/multipart-adapter.factory.mts +0 -21
  144. package/src/factories/reply.factory.mts +0 -21
  145. package/src/factories/request.factory.mts +0 -21
  146. package/src/factories/stream-adapter.factory.mts +0 -20
  147. package/src/factories/xml-stream-adapter.factory.mts +0 -20
  148. package/src/index.mts +0 -16
  149. package/src/interfaces/abstract-adapter.interface.mts +0 -32
  150. package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
  151. package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
  152. package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
  153. package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
  154. package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
  155. package/src/interfaces/adapter-environment.interface.mts +0 -74
  156. package/src/interfaces/can-activate.mts +0 -38
  157. package/src/interfaces/http-header.mts +0 -18
  158. package/src/interfaces/index.mts +0 -11
  159. package/src/interfaces/navios-module.mts +0 -28
  160. package/src/interfaces/plugin.interface.mts +0 -139
  161. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
  162. package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
  163. package/src/legacy-compat/attribute.factory.mts +0 -351
  164. package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
  165. package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
  166. package/src/legacy-compat/decorators/header.decorator.mts +0 -43
  167. package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
  168. package/src/legacy-compat/decorators/index.mts +0 -11
  169. package/src/legacy-compat/decorators/module.decorator.mts +0 -37
  170. package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
  171. package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
  172. package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
  173. package/src/legacy-compat/index.mts +0 -57
  174. package/src/logger/README.md +0 -3
  175. package/src/logger/console-logger.service.mts +0 -714
  176. package/src/logger/index.mts +0 -6
  177. package/src/logger/log-levels.mts +0 -21
  178. package/src/logger/logger-service.interface.mts +0 -42
  179. package/src/logger/logger.service.mts +0 -113
  180. package/src/logger/logger.tokens.mts +0 -44
  181. package/src/logger/utils/cli-colors.util.mts +0 -17
  182. package/src/logger/utils/filter-log-levelts.util.mts +0 -29
  183. package/src/logger/utils/index.mts +0 -5
  184. package/src/logger/utils/is-log-level-enabled.mts +0 -33
  185. package/src/logger/utils/is-log-level.util.mts +0 -10
  186. package/src/logger/utils/shared.utils.mts +0 -51
  187. package/src/metadata/controller.metadata.mts +0 -72
  188. package/src/metadata/handler.metadata.mts +0 -80
  189. package/src/metadata/index.mts +0 -4
  190. package/src/metadata/module.metadata.mts +0 -108
  191. package/src/metadata/navios-managed.metadata.mts +0 -42
  192. package/src/navios.application.mts +0 -484
  193. package/src/navios.environment.mts +0 -42
  194. package/src/navios.factory.mts +0 -158
  195. package/src/responders/enums/framework-error.enum.mts +0 -38
  196. package/src/responders/enums/index.mts +0 -1
  197. package/src/responders/index.mts +0 -4
  198. package/src/responders/interfaces/error-responder.interface.mts +0 -42
  199. package/src/responders/interfaces/error-response.interface.mts +0 -22
  200. package/src/responders/interfaces/index.mts +0 -3
  201. package/src/responders/interfaces/problem-details.interface.mts +0 -34
  202. package/src/responders/services/error-response-producer.service.mts +0 -143
  203. package/src/responders/services/forbidden-responder.service.mts +0 -77
  204. package/src/responders/services/index.mts +0 -5
  205. package/src/responders/services/internal-server-error-responder.service.mts +0 -57
  206. package/src/responders/services/not-found-responder.service.mts +0 -76
  207. package/src/responders/services/validation-error-responder.service.mts +0 -78
  208. package/src/responders/tokens/index.mts +0 -1
  209. package/src/responders/tokens/responder.tokens.mts +0 -84
  210. package/src/services/abstract-handler-adapter.service.mts +0 -366
  211. package/src/services/guard-runner.service.mts +0 -152
  212. package/src/services/index.mts +0 -4
  213. package/src/services/instance-resolver.service.mts +0 -177
  214. package/src/services/module-loader.service.mts +0 -252
  215. package/src/stores/index.mts +0 -1
  216. package/src/stores/request-id.store.mts +0 -85
  217. package/src/testing/index.mts +0 -3
  218. package/src/testing/testing-module.mts +0 -393
  219. package/src/testing/unit-testing-module.mts +0 -298
  220. package/src/tokens/adapter.token.mts +0 -6
  221. package/src/tokens/endpoint-adapter.token.mts +0 -8
  222. package/src/tokens/execution-context.token.mts +0 -9
  223. package/src/tokens/http-adapter.token.mts +0 -8
  224. package/src/tokens/index.mts +0 -10
  225. package/src/tokens/multipart-adapter.token.mts +0 -8
  226. package/src/tokens/navios-options.token.mts +0 -6
  227. package/src/tokens/reply.token.mts +0 -3
  228. package/src/tokens/request.token.mts +0 -3
  229. package/src/tokens/stream-adapter.token.mts +0 -8
  230. package/src/tokens/xml-stream-adapter.token.mts +0 -8
  231. package/src/utils/adapter-supports.util.mts +0 -47
  232. package/src/utils/index.mts +0 -1
  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,366 +0,0 @@
1
- import type { ClassType, ScopedContainer } from '@navios/di'
2
- import type { BaseEndpointOptions } from '@navios/builder'
3
-
4
- import { inject, optional } from '@navios/di'
5
-
6
- import type { HandlerMetadata } from '../metadata/index.mjs'
7
- import type {
8
- ArgumentGetterFn,
9
- FormatArgumentsFn as InterfaceFormatArgumentsFn,
10
- HttpHeader,
11
- } from '../interfaces/index.mjs'
12
- import type { NaviosApplicationOptions } from '../navios.application.mjs'
13
-
14
- import { NaviosOptionsToken } from '../tokens/index.mjs'
15
- import {
16
- InstanceResolverService,
17
- type InstanceResolution,
18
- } from './instance-resolver.service.mjs'
19
-
20
- // ============================================================================
21
- // Types
22
- // ============================================================================
23
-
24
- /**
25
- * Function type for argument getters that extract data from requests.
26
- * Re-exported from interface for convenience in adapter implementations.
27
- */
28
- export type ArgumentGetter<TRequest> = ArgumentGetterFn<TRequest>
29
-
30
- /**
31
- * Internal alias for FormatArgumentsFn from interface.
32
- * Not re-exported to avoid duplicate exports - use FormatArgumentsFn from interfaces instead.
33
- */
34
- type FormatArgumentsFn<TRequest> = InterfaceFormatArgumentsFn<TRequest>
35
-
36
- /**
37
- * Static handler - can be called without a scoped container.
38
- */
39
- export type AbstractStaticHandler<TRequest, TReply = void> = {
40
- isStatic: true
41
- handler: (request: TRequest, reply: TReply) => Promise<any>
42
- }
43
-
44
- /**
45
- * Dynamic handler - requires a scoped container for resolution.
46
- */
47
- export type AbstractDynamicHandler<TRequest, TReply = void> = {
48
- isStatic: false
49
- handler: (
50
- scoped: ScopedContainer,
51
- request: TRequest,
52
- reply: TReply,
53
- ) => Promise<any>
54
- }
55
-
56
- /**
57
- * Handler result - either static or dynamic.
58
- */
59
- export type AbstractHandlerResult<TRequest, TReply = void> =
60
- | AbstractStaticHandler<TRequest, TReply>
61
- | AbstractDynamicHandler<TRequest, TReply>
62
-
63
- /**
64
- * Context passed to handler creation methods.
65
- */
66
- export interface HandlerContext<
67
- TConfig extends BaseEndpointOptions = BaseEndpointOptions,
68
- > {
69
- methodName: string
70
- statusCode: number
71
- headers: Partial<Record<HttpHeader, number | string | string[] | undefined>>
72
- handlerMetadata: HandlerMetadata<TConfig>
73
- hasArguments: boolean
74
- }
75
-
76
- // ============================================================================
77
- // Default Options
78
- // ============================================================================
79
-
80
- const defaultOptions: NaviosApplicationOptions = {
81
- adapter: [],
82
- validateResponses: true,
83
- enableRequestId: false,
84
- }
85
-
86
- // ============================================================================
87
- // Abstract Base Class
88
- // ============================================================================
89
-
90
- /**
91
- * Abstract base class for HTTP handler adapter services.
92
- *
93
- * Provides shared logic for:
94
- * - Controller resolution (singleton vs request-scoped)
95
- * - Argument formatting (sync/async detection)
96
- * - Handler generation with static/dynamic branching
97
- * - Standardized error handling
98
- *
99
- * Adapters implement abstract methods for framework-specific behavior:
100
- * - Request parsing (query, body, URL params)
101
- * - Response creation
102
- * - Schema provision
103
- *
104
- * Supports all adapter types:
105
- * - Endpoint adapters: JSON request/response with validation
106
- * - Stream adapters: Streaming responses with extra context
107
- * - Multipart adapters: Form data parsing (extends endpoint)
108
- *
109
- * @typeParam TRequest - Framework request type (BunRequest, FastifyRequest)
110
- * @typeParam TReply - Framework reply type (void for Bun, FastifyReply)
111
- * @typeParam TConfig - Endpoint configuration type
112
- */
113
- export abstract class AbstractHandlerAdapterService<
114
- TRequest,
115
- TReply = void,
116
- TConfig extends BaseEndpointOptions = BaseEndpointOptions,
117
- > {
118
- protected instanceResolver = inject(InstanceResolverService)
119
- protected options = optional(NaviosOptionsToken) ?? defaultOptions
120
-
121
- // ==========================================================================
122
- // Abstract Methods - Must be implemented by adapters
123
- // ==========================================================================
124
-
125
- /**
126
- * Creates argument getter functions for extracting data from requests.
127
- *
128
- * Each getter populates a target object with data from the request
129
- * (query params, body, URL params, etc.).
130
- *
131
- * Implementation varies by adapter type:
132
- * - Endpoint: JSON body parsing with schema validation
133
- * - Stream: Same as endpoint (body + query + url params)
134
- * - Multipart: FormData/multipart stream parsing
135
- *
136
- * @param handlerMetadata - Handler metadata with schemas and configuration
137
- * @returns Array of getter functions
138
- */
139
- protected abstract createArgumentGetters(
140
- handlerMetadata: HandlerMetadata<TConfig>,
141
- ): ArgumentGetter<TRequest>[]
142
-
143
- /**
144
- * Creates a static handler for singleton controllers.
145
- *
146
- * Implementation varies by adapter type:
147
- * - Endpoint: Invoke method(args), serialize response as JSON
148
- * - Stream: Invoke method(args, streamContext), return Response/use reply
149
- *
150
- * @param boundMethod - Pre-bound controller method
151
- * @param formatArguments - Function to format request arguments
152
- * @param context - Handler context with metadata
153
- * @returns Static handler result
154
- */
155
- protected abstract createStaticHandler(
156
- boundMethod: (...args: any[]) => Promise<any>,
157
- formatArguments: FormatArgumentsFn<TRequest>,
158
- context: HandlerContext<TConfig>,
159
- ): AbstractStaticHandler<TRequest, TReply>
160
-
161
- /**
162
- * Creates a dynamic handler for request-scoped controllers.
163
- *
164
- * Implementation varies by adapter type:
165
- * - Endpoint: Resolve controller per-request, invoke method(args)
166
- * - Stream: Resolve controller per-request, invoke method(args, streamContext)
167
- *
168
- * @param resolution - Instance resolution with resolve function
169
- * @param formatArguments - Function to format request arguments
170
- * @param context - Handler context with metadata
171
- * @returns Dynamic handler result
172
- */
173
- protected abstract createDynamicHandler(
174
- resolution: InstanceResolution,
175
- formatArguments: FormatArgumentsFn<TRequest>,
176
- context: HandlerContext<TConfig>,
177
- ): AbstractDynamicHandler<TRequest, TReply>
178
-
179
- // ==========================================================================
180
- // Public Interface Methods
181
- // ==========================================================================
182
-
183
- /**
184
- * Prepares argument getters for parsing request data.
185
- *
186
- * Public alias for createArgumentGetters to satisfy interface contracts.
187
- * Subclasses should override createArgumentGetters instead.
188
- *
189
- * @param handlerMetadata - Handler metadata with schemas and configuration
190
- * @returns Array of getter functions
191
- */
192
- prepareArguments(
193
- handlerMetadata: HandlerMetadata<TConfig>,
194
- ): ArgumentGetter<TRequest>[] {
195
- return this.createArgumentGetters(handlerMetadata)
196
- }
197
-
198
- /**
199
- * Checks if the handler has any validation schemas defined.
200
- *
201
- * Override in subclasses to add additional schema checks
202
- * (e.g., response schema validation for endpoint adapters).
203
- *
204
- * @param handlerMetadata - Handler metadata with configuration
205
- * @returns true if handler has schemas
206
- */
207
- hasSchema(handlerMetadata: HandlerMetadata<TConfig>): boolean {
208
- const config = handlerMetadata.config
209
- return !!config.requestSchema || !!config.querySchema
210
- }
211
-
212
- /**
213
- * Provides schema information for the framework's validation system.
214
- *
215
- * Override in subclasses for frameworks that support schema registration
216
- * (e.g., Fastify). Default returns empty object (suitable for Bun).
217
- *
218
- * @param handlerMetadata - Handler metadata with configuration
219
- * @returns Schema object for framework registration
220
- */
221
- provideSchema(
222
- _handlerMetadata: HandlerMetadata<TConfig>,
223
- ): Record<string, any> {
224
- return {}
225
- }
226
-
227
- /**
228
- * Creates a request handler function for the endpoint.
229
- *
230
- * This method orchestrates the entire handler creation:
231
- * 1. Prepares argument getters for request parsing
232
- * 2. Builds optimized formatArguments function (sync/async)
233
- * 3. Resolves the controller (singleton vs request-scoped)
234
- * 4. Creates appropriate handler (static or dynamic)
235
- *
236
- * @param controller - Controller class containing the handler method
237
- * @param handlerMetadata - Handler metadata with configuration
238
- * @returns Handler result (static or dynamic)
239
- */
240
- async provideHandler(
241
- controller: ClassType,
242
- handlerMetadata: HandlerMetadata<TConfig>,
243
- ): Promise<AbstractHandlerResult<TRequest, TReply>> {
244
- // Prepare argument getters
245
- const getters = this.createArgumentGetters(handlerMetadata)
246
- const formatArguments = this.buildFormatArguments(getters)
247
- const hasArguments = getters.length > 0
248
-
249
- // Build handler context
250
- const context: HandlerContext<TConfig> = {
251
- methodName: handlerMetadata.classMethod,
252
- statusCode: handlerMetadata.successStatusCode,
253
- headers: handlerMetadata.headers,
254
- handlerMetadata,
255
- hasArguments,
256
- }
257
-
258
- // Resolve controller with automatic scope detection
259
- const resolution = await this.instanceResolver.resolve(controller)
260
-
261
- // Create appropriate handler based on resolution
262
- if (resolution.cached) {
263
- const cachedController = resolution.instance as any
264
- const boundMethod =
265
- cachedController[context.methodName].bind(cachedController)
266
- return this.createStaticHandler(boundMethod, formatArguments, context)
267
- }
268
-
269
- return this.createDynamicHandler(resolution, formatArguments, context)
270
- }
271
-
272
- // ==========================================================================
273
- // Public Utilities
274
- // ==========================================================================
275
-
276
- /**
277
- * Builds a formatArguments function from argument getters.
278
- *
279
- * Automatically detects sync vs async getters and optimizes accordingly:
280
- * - If all getters are sync: returns sync function (no Promise overhead)
281
- * - If any getter is async: returns async function with Promise.all
282
- * - If no getters: returns frozen empty object (zero allocation)
283
- *
284
- * This method is public to allow composition-based adapters (like XML adapter)
285
- * to reuse the optimized formatArguments logic without inheritance.
286
- *
287
- * @param getters - Array of argument getter functions
288
- * @returns Function to format arguments from request
289
- */
290
- buildFormatArguments(
291
- getters: ArgumentGetter<TRequest>[],
292
- ): FormatArgumentsFn<TRequest> {
293
- if (getters.length === 0) {
294
- const emptyArgs = Object.freeze({})
295
- return () => emptyArgs
296
- }
297
-
298
- // Detect if any getter is async at registration time
299
- const hasAsyncGetters = getters.some(
300
- (g) => g.constructor.name === 'AsyncFunction',
301
- )
302
-
303
- if (hasAsyncGetters) {
304
- return async (request: TRequest) => {
305
- const argument: Record<string, any> = {}
306
- const promises: Promise<void>[] = []
307
- for (const getter of getters) {
308
- const res = getter(argument, request)
309
- if (res instanceof Promise) {
310
- promises.push(res)
311
- }
312
- }
313
- await Promise.all(promises)
314
- return argument
315
- }
316
- }
317
-
318
- return (request: TRequest) => {
319
- const argument: Record<string, any> = {}
320
- for (const getter of getters) {
321
- getter(argument, request)
322
- }
323
- return argument
324
- }
325
- }
326
-
327
- // ==========================================================================
328
- // Protected Utilities
329
- // ==========================================================================
330
-
331
- /**
332
- * Checks if the URL pattern contains URL parameters.
333
- *
334
- * @param config - Endpoint configuration
335
- * @returns true if URL contains '$' parameter markers
336
- */
337
- protected hasUrlParams(config: TConfig): boolean {
338
- return config.url.includes('$')
339
- }
340
-
341
- /**
342
- * Wraps handler execution with standardized error handling.
343
- *
344
- * Re-throws HttpExceptions as-is for framework error handlers.
345
- * Other errors are re-thrown for global error handling.
346
- *
347
- * @param fn - Handler function to wrap
348
- * @returns Wrapped function with error handling
349
- */
350
- protected wrapWithErrorHandling<T extends (...args: any[]) => Promise<any>>(
351
- fn: T,
352
- ): T {
353
- return (async (...args: any[]) => {
354
- try {
355
- return await fn(...args)
356
- } catch (error) {
357
- // Re-throw HttpExceptions as-is for framework error handlers
358
- if (error && typeof error === 'object' && 'statusCode' in error) {
359
- throw error
360
- }
361
- // Re-throw unexpected errors for global error handling
362
- throw error
363
- }
364
- }) as T
365
- }
366
- }
@@ -1,152 +0,0 @@
1
- import type { ClassTypeWithInstance, ScopedContainer } from '@navios/di'
2
-
3
- import { inject, Injectable, InjectionToken } from '@navios/di'
4
-
5
- import type {
6
- AbstractExecutionContext,
7
- CanActivate,
8
- } from '../interfaces/index.mjs'
9
- import type {
10
- ControllerMetadata,
11
- HandlerMetadata,
12
- ModuleMetadata,
13
- } from '../metadata/index.mjs'
14
-
15
- import { HttpException } from '../exceptions/index.mjs'
16
- import { Logger } from '../logger/index.mjs'
17
- import { FrameworkError } from '../responders/enums/framework-error.enum.mjs'
18
- import { ErrorResponseProducerService } from '../responders/services/error-response-producer.service.mjs'
19
-
20
- @Injectable()
21
- export class GuardRunnerService {
22
- private readonly errorProducer = inject(ErrorResponseProducerService)
23
- private readonly logger = inject(Logger, {
24
- context: GuardRunnerService.name,
25
- })
26
-
27
- /**
28
- * Runs guards that need to be resolved from a scoped container.
29
- * Use this when guards have request-scoped dependencies.
30
- */
31
- async runGuards(
32
- allGuards: Set<
33
- | ClassTypeWithInstance<CanActivate>
34
- | InjectionToken<CanActivate, undefined>
35
- >,
36
- executionContext: AbstractExecutionContext,
37
- context: ScopedContainer,
38
- ) {
39
- // Reverse order: module guards run first, then controller, then endpoint
40
- const guardsArray = Array.from(allGuards).reverse()
41
-
42
- // Resolve all guards in parallel
43
- const guardInstances = await Promise.all(
44
- guardsArray.map(async (guard) => {
45
- const guardInstance = await context.get(
46
- guard as InjectionToken<CanActivate, undefined>,
47
- )
48
- if (!guardInstance.canActivate) {
49
- throw new Error(
50
- `[Navios] Guard ${guard.name as string} does not implement canActivate()`,
51
- )
52
- }
53
- return guardInstance
54
- }),
55
- )
56
-
57
- return this.executeGuards(guardInstances, executionContext)
58
- }
59
-
60
- /**
61
- * Runs pre-resolved guard instances.
62
- * Use this when all guards are singletons and have been pre-resolved at startup.
63
- */
64
- async runGuardsStatic(
65
- guardInstances: CanActivate[],
66
- executionContext: AbstractExecutionContext,
67
- ) {
68
- return this.executeGuards(guardInstances, executionContext)
69
- }
70
-
71
- /**
72
- * Shared guard execution logic.
73
- * Iterates through guard instances and calls canActivate on each.
74
- */
75
- private async executeGuards(
76
- guardInstances: CanActivate[],
77
- executionContext: AbstractExecutionContext,
78
- ): Promise<boolean> {
79
- let canActivate = true
80
- for (const guardInstance of guardInstances) {
81
- try {
82
- canActivate = await guardInstance.canActivate(executionContext)
83
- if (!canActivate) {
84
- break
85
- }
86
- } catch (error) {
87
- if (error instanceof HttpException) {
88
- executionContext
89
- .getReply()
90
- .status(error.statusCode)
91
- .send(error.response)
92
- return false
93
- } else {
94
- this.logger.error('Error running guard', error)
95
- const errorResponse = this.errorProducer.respond(
96
- FrameworkError.InternalServerError,
97
- error,
98
- )
99
- executionContext
100
- .getReply()
101
- .status(errorResponse.statusCode)
102
- .send(errorResponse.payload)
103
- return false
104
- }
105
- }
106
- }
107
- if (!canActivate) {
108
- const errorResponse = this.errorProducer.respond(
109
- FrameworkError.Forbidden,
110
- null,
111
- )
112
- executionContext
113
- .getReply()
114
- .status(errorResponse.statusCode)
115
- .send(errorResponse.payload)
116
- return false
117
- }
118
- return canActivate
119
- }
120
-
121
- makeContext(
122
- moduleMetadata: ModuleMetadata,
123
- controllerMetadata: ControllerMetadata,
124
- endpoint: HandlerMetadata,
125
- ): Set<
126
- ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>
127
- > {
128
- const guards = new Set<
129
- | ClassTypeWithInstance<CanActivate>
130
- | InjectionToken<CanActivate, undefined>
131
- >()
132
- const endpointGuards = endpoint.guards
133
- const controllerGuards = controllerMetadata.guards
134
- const moduleGuards = moduleMetadata.guards
135
- if (endpointGuards.size > 0) {
136
- for (const guard of endpointGuards) {
137
- guards.add(guard)
138
- }
139
- }
140
- if (controllerGuards.size > 0) {
141
- for (const guard of controllerGuards) {
142
- guards.add(guard)
143
- }
144
- }
145
- if (moduleGuards.size > 0) {
146
- for (const guard of moduleGuards) {
147
- guards.add(guard)
148
- }
149
- }
150
- return guards
151
- }
152
- }
@@ -1,4 +0,0 @@
1
- export * from './abstract-handler-adapter.service.mjs'
2
- export * from './instance-resolver.service.mjs'
3
- export * from './guard-runner.service.mjs'
4
- export * from './module-loader.service.mjs'
@@ -1,177 +0,0 @@
1
- import type { ClassType, ScopedContainer } from '@navios/di'
2
-
3
- import {
4
- Container,
5
- getInjectableToken,
6
- inject,
7
- Injectable,
8
- InjectableScope,
9
- } from '@navios/di'
10
-
11
- /**
12
- * Result of instance resolution attempt.
13
- * Contains either a cached singleton instance or a resolver function
14
- * that can be used to get a fresh instance per request.
15
- */
16
- export interface InstanceResolution<T = any> {
17
- /**
18
- * Whether the instance was successfully cached as a singleton.
19
- * If true, `instance` contains the cached instance.
20
- * If false, the class has request-scoped dependencies and
21
- * must be resolved per-request using `resolve()`.
22
- */
23
- cached: boolean
24
-
25
- /**
26
- * The cached instance (only available if `cached` is true).
27
- */
28
- instance: T | null
29
-
30
- /**
31
- * Resolves the instance from a scoped container.
32
- * Use this when `cached` is false to get a fresh instance per request.
33
- */
34
- resolve: (scoped: ScopedContainer) => Promise<T>
35
- }
36
-
37
- /**
38
- * Result of resolving multiple instances.
39
- * Contains either all cached singleton instances or a resolver function.
40
- */
41
- export interface MultiInstanceResolution<T = any> {
42
- /**
43
- * Whether ALL instances were successfully cached as singletons.
44
- * If true, `instances` contains all cached instances.
45
- * If false, at least one class has request-scoped dependencies.
46
- */
47
- cached: boolean
48
-
49
- /**
50
- * The cached instances (only available if `cached` is true).
51
- * Order matches the input array order.
52
- */
53
- instances: T[] | null
54
-
55
- /**
56
- * The original class types for dynamic resolution.
57
- */
58
- classTypes: ClassType[]
59
-
60
- /**
61
- * Resolves all instances from a scoped container.
62
- * Use this when `cached` is false to get fresh instances per request.
63
- */
64
- resolve: (scoped: ScopedContainer) => Promise<T[]>
65
- }
66
-
67
- /**
68
- * Service responsible for resolving class instances with automatic scope detection.
69
- *
70
- * This service attempts to resolve classes as singletons from the root container.
71
- * If resolution fails (because the class has request-scoped dependencies),
72
- * it automatically updates the class's scope to Request and provides a
73
- * resolver function for per-request instantiation.
74
- *
75
- * This enables optimal performance:
76
- * - Classes without request-scoped deps stay as singletons (faster)
77
- * - Classes with request-scoped deps are automatically promoted to request scope
78
- *
79
- * @example
80
- * ```ts
81
- * const resolution = await instanceResolver.resolve(UserController)
82
- *
83
- * if (resolution.cached) {
84
- * // Use cached singleton
85
- * return resolution.instance.handleRequest(req)
86
- * } else {
87
- * // Resolve per request
88
- * const controller = await resolution.resolve(scopedContainer)
89
- * return controller.handleRequest(req)
90
- * }
91
- * ```
92
- */
93
- @Injectable()
94
- export class InstanceResolverService {
95
- private container = inject(Container)
96
-
97
- /**
98
- * Attempts to resolve a class instance, automatically detecting if it needs
99
- * request scope based on its dependencies.
100
- *
101
- * @param classType - The class to resolve
102
- * @returns A resolution result containing either a cached instance or resolver function
103
- */
104
- async resolve<T>(classType: ClassType): Promise<InstanceResolution<T>> {
105
- let cachedInstance: T | null = null
106
-
107
- try {
108
- cachedInstance = await this.container.get(classType)
109
- } catch {
110
- // Class has request-scoped dependencies, update its scope to Request
111
- // so it will be resolved per-request from the scoped container
112
- const token = getInjectableToken(classType)
113
- this.container.getRegistry().updateScope(token, InjectableScope.Request)
114
- }
115
-
116
- return {
117
- cached: cachedInstance !== null,
118
- instance: cachedInstance,
119
- resolve: (scoped: ScopedContainer) => scoped.get(classType) as Promise<T>,
120
- }
121
- }
122
-
123
- /**
124
- * Attempts to resolve multiple class instances, automatically detecting if any need
125
- * request scope based on their dependencies.
126
- *
127
- * Returns `cached: true` only if ALL classes can be resolved as singletons.
128
- * If any class has request-scoped dependencies, returns `cached: false`.
129
- *
130
- * @param classTypes - The classes to resolve
131
- * @returns A resolution result containing either all cached instances or resolver function
132
- */
133
- async resolveMany<T>(
134
- classTypes: ClassType[],
135
- ): Promise<MultiInstanceResolution<T>> {
136
- if (classTypes.length === 0) {
137
- return {
138
- cached: true,
139
- instances: [],
140
- classTypes: [],
141
- resolve: async () => [],
142
- }
143
- }
144
-
145
- // Resolve all classes in parallel
146
- const results = await Promise.all(
147
- classTypes.map(async (classType) => {
148
- try {
149
- const instance = await this.container.get(classType)
150
- return { success: true, instance: instance as T }
151
- } catch {
152
- // Class has request-scoped dependencies, update its scope to Request
153
- const token = getInjectableToken(classType)
154
- this.container
155
- .getRegistry()
156
- .updateScope(token, InjectableScope.Request)
157
- return { success: false, instance: null }
158
- }
159
- }),
160
- )
161
-
162
- const allCached = results.every((r) => r.success)
163
- const cachedInstances = allCached
164
- ? results.map((r) => r.instance as T)
165
- : null
166
-
167
- return {
168
- cached: allCached,
169
- instances: cachedInstances,
170
- classTypes,
171
- resolve: (scoped: ScopedContainer) =>
172
- Promise.all(
173
- classTypes.map((classType) => scoped.get(classType) as Promise<T>),
174
- ),
175
- }
176
- }
177
- }