@navios/core 0.1.14 → 0.2.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 (71) hide show
  1. package/dist/_tsup-dts-rollup.d.mts +185 -434
  2. package/dist/_tsup-dts-rollup.d.ts +185 -434
  3. package/dist/index.d.mts +62 -46
  4. package/dist/index.d.ts +62 -46
  5. package/dist/index.js +482 -1328
  6. package/dist/index.mjs +484 -1292
  7. package/package.json +3 -2
  8. package/src/adapters/endpoint-adapter.service.mts +72 -0
  9. package/src/adapters/handler-adapter.interface.mts +21 -0
  10. package/src/adapters/index.mts +4 -0
  11. package/src/adapters/multipart-adapter.service.mts +131 -0
  12. package/src/adapters/stream-adapter.service.mts +91 -0
  13. package/src/attribute.factory.mts +14 -14
  14. package/src/config/config.provider.mts +16 -12
  15. package/src/decorators/controller.decorator.mts +3 -8
  16. package/src/decorators/endpoint.decorator.mts +7 -3
  17. package/src/decorators/header.decorator.mts +1 -6
  18. package/src/decorators/http-code.decorator.mts +1 -6
  19. package/src/decorators/module.decorator.mts +16 -21
  20. package/src/decorators/multipart.decorator.mts +7 -3
  21. package/src/decorators/stream.decorator.mts +7 -3
  22. package/src/decorators/use-guards.decorator.mts +3 -2
  23. package/src/index.mts +2 -1
  24. package/src/logger/console-logger.service.mts +3 -2
  25. package/src/logger/logger.factory.mts +4 -5
  26. package/src/logger/logger.service.mts +2 -2
  27. package/src/metadata/controller.metadata.mts +6 -5
  28. package/src/metadata/{endpoint.metadata.mts → handler.metadata.mts} +18 -28
  29. package/src/metadata/index.mts +1 -2
  30. package/src/metadata/module.metadata.mts +3 -2
  31. package/src/navios.application.mts +12 -12
  32. package/src/navios.factory.mts +4 -2
  33. package/src/services/controller-adapter.service.mts +65 -245
  34. package/src/services/execution-context.mts +4 -3
  35. package/src/services/guard-runner.service.mts +4 -6
  36. package/src/services/module-loader.service.mts +4 -2
  37. package/src/tokens/application.token.mts +1 -1
  38. package/src/tokens/execution-context.token.mts +2 -1
  39. package/src/tokens/reply.token.mts +1 -1
  40. package/src/tokens/request.token.mts +1 -1
  41. package/src/metadata/injectable.metadata.mts +0 -11
  42. package/src/service-locator/__tests__/injectable.spec.mts +0 -171
  43. package/src/service-locator/__tests__/injection-token.spec.mts +0 -124
  44. package/src/service-locator/decorators/get-injectable-token.mts +0 -19
  45. package/src/service-locator/decorators/index.mts +0 -2
  46. package/src/service-locator/decorators/injectable.decorator.mts +0 -64
  47. package/src/service-locator/enums/index.mts +0 -1
  48. package/src/service-locator/enums/injectable-scope.enum.mts +0 -10
  49. package/src/service-locator/errors/errors.enum.mts +0 -8
  50. package/src/service-locator/errors/factory-not-found.mts +0 -8
  51. package/src/service-locator/errors/factory-token-not-resolved.mts +0 -10
  52. package/src/service-locator/errors/index.mts +0 -7
  53. package/src/service-locator/errors/instance-destroying.mts +0 -8
  54. package/src/service-locator/errors/instance-expired.mts +0 -8
  55. package/src/service-locator/errors/instance-not-found.mts +0 -8
  56. package/src/service-locator/errors/unknown-error.mts +0 -15
  57. package/src/service-locator/event-emitter.mts +0 -107
  58. package/src/service-locator/index.mts +0 -15
  59. package/src/service-locator/inject.mts +0 -28
  60. package/src/service-locator/injection-token.mts +0 -92
  61. package/src/service-locator/injector.mts +0 -18
  62. package/src/service-locator/interfaces/factory.interface.mts +0 -3
  63. package/src/service-locator/override.mts +0 -22
  64. package/src/service-locator/proxy-service-locator.mts +0 -99
  65. package/src/service-locator/resolve-service.mts +0 -46
  66. package/src/service-locator/service-locator-abstract-factory-context.mts +0 -23
  67. package/src/service-locator/service-locator-event-bus.mts +0 -96
  68. package/src/service-locator/service-locator-instance-holder.mts +0 -63
  69. package/src/service-locator/service-locator-manager.mts +0 -89
  70. package/src/service-locator/service-locator.mts +0 -535
  71. package/src/service-locator/sync-injector.mts +0 -52
package/dist/index.js CHANGED
@@ -5,15 +5,15 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __knownSymbol = (name2, symbol) => (symbol = Symbol[name2]) ? symbol : Symbol.for("Symbol." + name2);
8
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
9
9
  var __typeError = (msg) => {
10
10
  throw TypeError(msg);
11
11
  };
12
12
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
13
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
14
14
  var __export = (target, all) => {
15
- for (var name2 in all)
16
- __defProp(target, name2, { get: all[name2], enumerable: true });
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
17
  };
18
18
  var __copyProps = (to, from, except, desc) => {
19
19
  if (from && typeof from === "object" || typeof from === "function") {
@@ -23,6 +23,7 @@ var __copyProps = (to, from, except, desc) => {
23
23
  }
24
24
  return to;
25
25
  };
26
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
26
27
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
28
  // If the importer is in node compatibility mode or this is not an ESM
28
29
  // file that has been converted to a CommonJS file using a Babel-
@@ -35,35 +36,35 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
35
36
  var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
36
37
  var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
37
38
  var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
38
- var __decoratorContext = (kind, name2, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name: name2, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
39
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
39
40
  var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
40
41
  var __runInitializers = (array, flags, self, value) => {
41
42
  for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
42
43
  return value;
43
44
  };
44
- var __decorateElement = (array, flags, name2, decorators, target, extra) => {
45
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
45
46
  var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
46
47
  var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
47
48
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
48
- var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name2]() {
49
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
49
50
  return __privateGet(this, extra);
50
- }, set [name2](x) {
51
+ }, set [name](x) {
51
52
  return __privateSet(this, extra, x);
52
- } }, name2));
53
- k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name2) : __name(target, name2);
53
+ } }, name));
54
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
54
55
  for (var i = decorators.length - 1; i >= 0; i--) {
55
- ctx = __decoratorContext(k, name2, done = {}, array[3], extraInitializers);
56
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
56
57
  if (k) {
57
- ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name2 in x };
58
- if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name2];
59
- if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name2] = y;
58
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
59
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
60
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
60
61
  }
61
62
  it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
62
63
  if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
63
64
  else if (typeof it !== "object" || it === null) __typeError("Object expected");
64
65
  else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
65
66
  }
66
- return k || __decoratorMetadata(array, target), desc && __defProp(target, name2, desc), p ? k ^ 4 ? extra : desc : target;
67
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
67
68
  };
68
69
  var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
69
70
  var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
@@ -77,7 +78,6 @@ __export(src_exports, {
77
78
  Application: () => Application,
78
79
  AttributeFactory: () => AttributeFactory,
79
80
  BadRequestException: () => BadRequestException,
80
- BoundInjectionToken: () => BoundInjectionToken,
81
81
  ConfigProvider: () => ConfigProvider,
82
82
  ConfigProviderFactory: () => ConfigProviderFactory,
83
83
  ConfigProviderOptions: () => ConfigProviderOptions,
@@ -88,29 +88,17 @@ __export(src_exports, {
88
88
  ControllerAdapterService: () => ControllerAdapterService,
89
89
  ControllerMetadataKey: () => ControllerMetadataKey,
90
90
  Endpoint: () => Endpoint,
91
+ EndpointAdapterService: () => EndpointAdapterService,
92
+ EndpointAdapterToken: () => EndpointAdapterToken,
91
93
  EndpointMetadataKey: () => EndpointMetadataKey,
92
- EndpointType: () => EndpointType,
93
- ErrorsEnum: () => ErrorsEnum,
94
- EventEmitter: () => EventEmitter,
95
94
  ExecutionContext: () => ExecutionContext,
96
95
  ExecutionContextInjectionToken: () => ExecutionContextInjectionToken,
97
96
  ExecutionContextToken: () => ExecutionContextToken,
98
- FactoryInjectionToken: () => FactoryInjectionToken,
99
- FactoryNotFound: () => FactoryNotFound,
100
- FactoryTokenNotResolved: () => FactoryTokenNotResolved,
101
97
  ForbiddenException: () => ForbiddenException,
102
98
  GuardRunnerService: () => GuardRunnerService,
103
99
  Header: () => Header,
104
100
  HttpCode: () => HttpCode,
105
101
  HttpException: () => HttpException,
106
- Injectable: () => Injectable,
107
- InjectableScope: () => InjectableScope,
108
- InjectableTokenMeta: () => InjectableTokenMeta,
109
- InjectableType: () => InjectableType,
110
- InjectionToken: () => InjectionToken,
111
- InstanceDestroying: () => InstanceDestroying,
112
- InstanceExpired: () => InstanceExpired,
113
- InstanceNotFound: () => InstanceNotFound,
114
102
  InternalServerErrorException: () => InternalServerErrorException,
115
103
  LOG_LEVELS: () => LOG_LEVELS,
116
104
  Logger: () => Logger,
@@ -122,20 +110,18 @@ __export(src_exports, {
122
110
  ModuleLoaderService: () => ModuleLoaderService,
123
111
  ModuleMetadataKey: () => ModuleMetadataKey,
124
112
  Multipart: () => Multipart,
113
+ MultipartAdapterService: () => MultipartAdapterService,
114
+ MultipartAdapterToken: () => MultipartAdapterToken,
125
115
  NaviosApplication: () => NaviosApplication,
126
116
  NaviosFactory: () => NaviosFactory,
127
117
  NotFoundException: () => NotFoundException,
128
118
  PinoWrapper: () => PinoWrapper,
129
119
  Reply: () => Reply,
130
120
  Request: () => Request,
131
- ServiceLocator: () => ServiceLocator,
132
- ServiceLocatorEventBus: () => ServiceLocatorEventBus,
133
- ServiceLocatorInstanceHolderKind: () => ServiceLocatorInstanceHolderKind,
134
- ServiceLocatorInstanceHolderStatus: () => ServiceLocatorInstanceHolderStatus,
135
- ServiceLocatorManager: () => ServiceLocatorManager,
136
121
  Stream: () => Stream,
122
+ StreamAdapterService: () => StreamAdapterService,
123
+ StreamAdapterToken: () => StreamAdapterToken,
137
124
  UnauthorizedException: () => UnauthorizedException,
138
- UnknownError: () => UnknownError,
139
125
  UseGuards: () => UseGuards,
140
126
  addLeadingSlash: () => addLeadingSlash,
141
127
  clc: () => clc,
@@ -147,12 +133,9 @@ __export(src_exports, {
147
133
  getAllEndpointMetadata: () => getAllEndpointMetadata,
148
134
  getControllerMetadata: () => getControllerMetadata,
149
135
  getEndpointMetadata: () => getEndpointMetadata,
150
- getInjectableToken: () => getInjectableToken,
151
136
  getModuleMetadata: () => getModuleMetadata,
152
- getServiceLocator: () => getServiceLocator,
153
137
  hasControllerMetadata: () => hasControllerMetadata,
154
138
  hasModuleMetadata: () => hasModuleMetadata,
155
- inject: () => inject,
156
139
  isConstructor: () => isConstructor,
157
140
  isEmpty: () => isEmpty,
158
141
  isFunction: () => isFunction,
@@ -166,16 +149,235 @@ __export(src_exports, {
166
149
  isSymbol: () => isSymbol,
167
150
  isUndefined: () => isUndefined,
168
151
  normalizePath: () => normalizePath,
169
- override: () => override,
170
152
  provideConfig: () => provideConfig,
171
- provideServiceLocator: () => provideServiceLocator,
172
- resolveService: () => resolveService,
173
- setPromiseCollector: () => setPromiseCollector,
174
153
  stripEndSlash: () => stripEndSlash,
175
- syncInject: () => syncInject,
176
154
  yellow: () => yellow
177
155
  });
178
156
  module.exports = __toCommonJS(src_exports);
157
+ __reExport(src_exports, require("@navios/di"), module.exports);
158
+
159
+ // packages/core/src/adapters/endpoint-adapter.service.mts
160
+ var import_di2 = require("@navios/di");
161
+
162
+ // packages/core/src/adapters/stream-adapter.service.mts
163
+ var import_di = require("@navios/di");
164
+ var StreamAdapterToken = import_di.InjectionToken.create(
165
+ Symbol.for("StreamAdapterService")
166
+ );
167
+ var _StreamAdapterService_decorators, _init;
168
+ _StreamAdapterService_decorators = [(0, import_di.Injectable)({
169
+ token: StreamAdapterToken
170
+ })];
171
+ var StreamAdapterService = class {
172
+ hasSchema(handlerMetadata) {
173
+ const config = handlerMetadata.config;
174
+ return !!config.requestSchema || !!config.querySchema;
175
+ }
176
+ prepareArguments(handlerMetadata) {
177
+ const config = handlerMetadata.config;
178
+ const getters = [];
179
+ if (config.querySchema) {
180
+ getters.push((target, request) => {
181
+ target.params = request.query;
182
+ });
183
+ }
184
+ if (config.requestSchema) {
185
+ getters.push((target, request) => {
186
+ target.data = request.body;
187
+ });
188
+ }
189
+ if (config.url.includes("$")) {
190
+ getters.push((target, request) => {
191
+ target.urlParams = request.params;
192
+ });
193
+ }
194
+ return getters;
195
+ }
196
+ provideHandler(controller, executionContext, handlerMetadata) {
197
+ const getters = this.prepareArguments(handlerMetadata);
198
+ const formatArguments = async (request) => {
199
+ const argument = {};
200
+ const promises = [];
201
+ for (const getter of getters) {
202
+ const res = getter(argument, request);
203
+ if (res instanceof Promise) {
204
+ promises.push(res);
205
+ }
206
+ }
207
+ await Promise.all(promises);
208
+ return argument;
209
+ };
210
+ return async function(request, reply) {
211
+ const controllerInstance = await (0, import_di.inject)(controller);
212
+ const argument = await formatArguments(request);
213
+ await controllerInstance[handlerMetadata.classMethod](argument, reply);
214
+ };
215
+ }
216
+ provideSchema(handlerMetadata) {
217
+ const schema = {};
218
+ const { querySchema, requestSchema } = handlerMetadata.config;
219
+ if (querySchema) {
220
+ schema.querystring = querySchema;
221
+ }
222
+ if (requestSchema) {
223
+ schema.body = requestSchema;
224
+ }
225
+ return schema;
226
+ }
227
+ };
228
+ _init = __decoratorStart(null);
229
+ StreamAdapterService = __decorateElement(_init, 0, "StreamAdapterService", _StreamAdapterService_decorators, StreamAdapterService);
230
+ __runInitializers(_init, 1, StreamAdapterService);
231
+
232
+ // packages/core/src/adapters/endpoint-adapter.service.mts
233
+ var EndpointAdapterToken = import_di2.InjectionToken.create(
234
+ Symbol.for("EndpointAdapterService")
235
+ );
236
+ var _EndpointAdapterService_decorators, _init2, _a;
237
+ _EndpointAdapterService_decorators = [(0, import_di2.Injectable)({
238
+ token: EndpointAdapterToken
239
+ })];
240
+ var EndpointAdapterService = class extends (_a = StreamAdapterService) {
241
+ hasSchema(handlerMetadata) {
242
+ const config = handlerMetadata.config;
243
+ return super.hasSchema(handlerMetadata) || !!config.responseSchema;
244
+ }
245
+ provideSchema(handlerMetadata) {
246
+ const config = handlerMetadata.config;
247
+ const schema = super.provideSchema(handlerMetadata);
248
+ if (config.responseSchema) {
249
+ schema.response = {
250
+ 200: config.responseSchema
251
+ };
252
+ }
253
+ return schema;
254
+ }
255
+ provideHandler(controller, executionContext, handlerMetadata) {
256
+ const getters = this.prepareArguments(handlerMetadata);
257
+ const formatArguments = async (request) => {
258
+ const argument = {};
259
+ const promises = [];
260
+ for (const getter of getters) {
261
+ const res = getter(argument, request);
262
+ if (res instanceof Promise) {
263
+ promises.push(res);
264
+ }
265
+ }
266
+ await Promise.all(promises);
267
+ return argument;
268
+ };
269
+ return async function(request, reply) {
270
+ const controllerInstance = await (0, import_di2.inject)(controller);
271
+ const argument = await formatArguments(request);
272
+ const result = await controllerInstance[handlerMetadata.classMethod](argument);
273
+ reply.status(handlerMetadata.successStatusCode).headers(handlerMetadata.headers).send(result);
274
+ };
275
+ }
276
+ };
277
+ _init2 = __decoratorStart(_a);
278
+ EndpointAdapterService = __decorateElement(_init2, 0, "EndpointAdapterService", _EndpointAdapterService_decorators, EndpointAdapterService);
279
+ __runInitializers(_init2, 1, EndpointAdapterService);
280
+
281
+ // packages/core/src/adapters/multipart-adapter.service.mts
282
+ var import_di3 = require("@navios/di");
283
+ var import_zod = require("zod");
284
+ var MultipartAdapterToken = import_di3.InjectionToken.create(
285
+ Symbol.for("MultipartAdapterService")
286
+ );
287
+ var _MultipartAdapterService_decorators, _init3, _a2;
288
+ _MultipartAdapterService_decorators = [(0, import_di3.Injectable)({
289
+ token: MultipartAdapterToken
290
+ })];
291
+ var MultipartAdapterService = class extends (_a2 = EndpointAdapterService) {
292
+ prepareArguments(handlerMetadata) {
293
+ const config = handlerMetadata.config;
294
+ const getters = [];
295
+ if (config.querySchema) {
296
+ getters.push((target, request) => {
297
+ target.params = request.query;
298
+ });
299
+ }
300
+ if (config.url.includes("$")) {
301
+ getters.push((target, request) => {
302
+ target.urlParams = request.params;
303
+ });
304
+ }
305
+ const requestSchema = config.requestSchema;
306
+ const shape = requestSchema._def.shape();
307
+ const structure = this.analyzeSchema(shape);
308
+ getters.push(async (target, request) => {
309
+ const req = {};
310
+ for await (const part of request.parts()) {
311
+ await this.populateRequest(structure, part, req);
312
+ }
313
+ target.data = requestSchema.parse(req);
314
+ });
315
+ return getters;
316
+ }
317
+ async populateRequest(structure, part, req) {
318
+ const { isArray, isObject: isObject2 } = structure[part.fieldname] ?? {};
319
+ if (isArray && !req[part.fieldname]) {
320
+ req[part.fieldname] = [];
321
+ }
322
+ let value;
323
+ if (part.type === "file") {
324
+ value = new File([await part.toBuffer()], part.filename, {
325
+ type: part.mimetype
326
+ });
327
+ } else {
328
+ value = part.value;
329
+ if (isObject2 && typeof value === "string") {
330
+ value = JSON.parse(value);
331
+ }
332
+ }
333
+ if (isArray) {
334
+ req[part.fieldname].push(value);
335
+ } else {
336
+ req[part.fieldname] = value;
337
+ }
338
+ }
339
+ analyzeSchema(shape) {
340
+ return Object.keys(shape).reduce(
341
+ (target, key) => {
342
+ let schema = shape[key];
343
+ const isOptional = schema instanceof import_zod.ZodOptional;
344
+ if (isOptional) {
345
+ schema = schema.unwrap();
346
+ }
347
+ const isArray = schema instanceof import_zod.ZodArray;
348
+ if (isArray) {
349
+ schema = schema.element;
350
+ }
351
+ const isObject2 = schema instanceof import_zod.ZodObject;
352
+ return {
353
+ ...target,
354
+ [key]: {
355
+ isArray,
356
+ isOptional,
357
+ isObject: isObject2
358
+ }
359
+ };
360
+ },
361
+ {}
362
+ );
363
+ }
364
+ provideSchema(handlerMetadata) {
365
+ const schema = {};
366
+ const { querySchema, responseSchema } = handlerMetadata.config;
367
+ if (querySchema) {
368
+ schema.querystring = querySchema;
369
+ }
370
+ if (responseSchema) {
371
+ schema.response = {
372
+ 200: responseSchema
373
+ };
374
+ }
375
+ return schema;
376
+ }
377
+ };
378
+ _init3 = __decoratorStart(_a2);
379
+ MultipartAdapterService = __decorateElement(_init3, 0, "MultipartAdapterService", _MultipartAdapterService_decorators, MultipartAdapterService);
380
+ __runInitializers(_init3, 1, MultipartAdapterService);
179
381
 
180
382
  // packages/core/src/config/utils/helpers.mts
181
383
  var import_node_process = require("process");
@@ -188,7 +390,8 @@ function envString(key, defaultValue) {
188
390
  }
189
391
 
190
392
  // packages/core/src/config/config.provider.mts
191
- var import_zod4 = require("zod");
393
+ var import_di14 = require("@navios/di");
394
+ var import_zod3 = require("zod");
192
395
 
193
396
  // packages/core/src/logger/utils/cli-colors.util.mts
194
397
  var isColorAllowed = () => !process.env.NO_COLOR;
@@ -248,14 +451,14 @@ var LOG_LEVEL_VALUES = {
248
451
  fatal: 5
249
452
  };
250
453
  function isLogLevelEnabled(targetLevel, logLevels) {
251
- var _a;
454
+ var _a3;
252
455
  if (!logLevels || Array.isArray(logLevels) && (logLevels == null ? void 0 : logLevels.length) === 0) {
253
456
  return false;
254
457
  }
255
458
  if (logLevels.includes(targetLevel)) {
256
459
  return true;
257
460
  }
258
- const highestLogLevelValue = (_a = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)) == null ? void 0 : _a[0];
461
+ const highestLogLevelValue = (_a3 = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)) == null ? void 0 : _a3[0];
259
462
  const targetLevelValue = LOG_LEVEL_VALUES[targetLevel];
260
463
  return targetLevelValue >= highestLogLevelValue;
261
464
  }
@@ -287,912 +490,23 @@ var isSymbol = (val) => typeof val === "symbol";
287
490
 
288
491
  // packages/core/src/logger/console-logger.service.mts
289
492
  var import_util = require("util");
290
-
291
- // packages/core/src/service-locator/decorators/injectable.decorator.mts
292
- var import_common2 = require("@navios/common");
293
-
294
- // packages/core/src/service-locator/enums/injectable-scope.enum.mts
295
- var InjectableScope = /* @__PURE__ */ ((InjectableScope2) => {
296
- InjectableScope2["Singleton"] = "Singleton";
297
- InjectableScope2["Instance"] = "Instance";
298
- return InjectableScope2;
299
- })(InjectableScope || {});
300
-
301
- // packages/core/src/service-locator/injection-token.mts
302
- var import_crypto = require("crypto");
303
- var import_zod = require("zod");
304
- var InjectionToken = class _InjectionToken {
305
- constructor(name2, schema) {
306
- this.name = name2;
307
- this.schema = schema;
308
- }
309
- id = (0, import_crypto.randomUUID)();
310
- static create(name2, schema) {
311
- return new _InjectionToken(name2, schema);
312
- }
313
- static bound(token, value) {
314
- return new BoundInjectionToken(token, value);
315
- }
316
- static factory(token, factory) {
317
- return new FactoryInjectionToken(token, factory);
318
- }
319
- static refineType(token) {
320
- return token;
321
- }
322
- };
323
- var BoundInjectionToken = class extends InjectionToken {
324
- constructor(token, value) {
325
- super(token.name, token.schema);
326
- this.token = token;
327
- this.value = value;
328
- this.id = token.id;
329
- }
330
- };
331
- var FactoryInjectionToken = class extends InjectionToken {
332
- constructor(token, factory) {
333
- super(token.name, token.schema);
334
- this.token = token;
335
- this.factory = factory;
336
- }
337
- value;
338
- resolved = false;
339
- async resolve() {
340
- if (!this.value) {
341
- this.value = await this.factory();
342
- this.resolved = true;
343
- }
344
- return this.value;
345
- }
346
- };
347
-
348
- // packages/core/src/service-locator/errors/errors.enum.mts
349
- var ErrorsEnum = /* @__PURE__ */ ((ErrorsEnum2) => {
350
- ErrorsEnum2["InstanceExpired"] = "InstanceExpired";
351
- ErrorsEnum2["InstanceNotFound"] = "InstanceNotFound";
352
- ErrorsEnum2["InstanceDestroying"] = "InstanceDestroying";
353
- ErrorsEnum2["UnknownError"] = "UnknownError";
354
- ErrorsEnum2["FactoryNotFound"] = "FactoryNotFound";
355
- ErrorsEnum2["FactoryTokenNotResolved"] = "FactoryTokenNotResolved";
356
- return ErrorsEnum2;
357
- })(ErrorsEnum || {});
358
-
359
- // packages/core/src/service-locator/errors/factory-not-found.mts
360
- var FactoryNotFound = class extends Error {
361
- constructor(name2) {
362
- super(`Factory ${name2} not found`);
363
- this.name = name2;
364
- }
365
- code = "FactoryNotFound" /* FactoryNotFound */;
366
- };
367
-
368
- // packages/core/src/service-locator/errors/factory-token-not-resolved.mts
369
- var FactoryTokenNotResolved = class extends Error {
370
- code = "FactoryTokenNotResolved" /* FactoryTokenNotResolved */;
371
- constructor(name2) {
372
- super(`Factory token not resolved: ${name2.toString()}`);
373
- }
374
- };
375
-
376
- // packages/core/src/service-locator/errors/instance-destroying.mts
377
- var InstanceDestroying = class extends Error {
378
- constructor(name2) {
379
- super(`Instance ${name2} destroying`);
380
- this.name = name2;
381
- }
382
- code = "InstanceDestroying" /* InstanceDestroying */;
383
- };
384
-
385
- // packages/core/src/service-locator/errors/instance-expired.mts
386
- var InstanceExpired = class extends Error {
387
- constructor(name2) {
388
- super(`Instance ${name2} expired`);
389
- this.name = name2;
390
- }
391
- code = "InstanceExpired" /* InstanceExpired */;
392
- };
393
-
394
- // packages/core/src/service-locator/errors/instance-not-found.mts
395
- var InstanceNotFound = class extends Error {
396
- constructor(name2) {
397
- super(`Instance ${name2} not found`);
398
- this.name = name2;
399
- }
400
- code = "InstanceNotFound" /* InstanceNotFound */;
401
- };
402
-
403
- // packages/core/src/service-locator/errors/unknown-error.mts
404
- var UnknownError = class extends Error {
405
- code = "UnknownError" /* UnknownError */;
406
- parent;
407
- constructor(message) {
408
- if (message instanceof Error) {
409
- super(message.message);
410
- this.parent = message;
411
- return;
412
- }
413
- super(message);
414
- }
415
- };
416
-
417
- // packages/core/src/service-locator/service-locator-event-bus.mts
418
- var ServiceLocatorEventBus = class {
419
- constructor(logger = null) {
420
- this.logger = logger;
421
- }
422
- listeners = /* @__PURE__ */ new Map();
423
- on(ns, event, listener) {
424
- var _a;
425
- (_a = this.logger) == null ? void 0 : _a.debug(`[ServiceLocatorEventBus]#on(): ns:${ns} event:${event}`);
426
- if (!this.listeners.has(ns)) {
427
- this.listeners.set(ns, /* @__PURE__ */ new Map());
428
- }
429
- const nsEvents = this.listeners.get(ns);
430
- if (!nsEvents.has(event)) {
431
- nsEvents.set(event, /* @__PURE__ */ new Set());
432
- }
433
- nsEvents.get(event).add(listener);
434
- return () => {
435
- var _a2;
436
- nsEvents.get(event).delete(listener);
437
- if (((_a2 = nsEvents.get(event)) == null ? void 0 : _a2.size) === 0) {
438
- nsEvents.delete(event);
439
- }
440
- if (nsEvents.size === 0) {
441
- this.listeners.delete(ns);
442
- }
443
- };
444
- }
445
- async emit(key, event) {
446
- var _a, _b, _c;
447
- if (!this.listeners.has(key)) {
448
- return;
449
- }
450
- const events = this.listeners.get(key);
451
- const preEvent = `pre:${event}`;
452
- const postEvent = `post:${event}`;
453
- (_a = this.logger) == null ? void 0 : _a.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${preEvent}`);
454
- await Promise.allSettled(
455
- [...events.get(preEvent) ?? []].map((listener) => listener(preEvent))
456
- ).then((results) => {
457
- results.filter((result) => result.status === "rejected").forEach((result) => {
458
- var _a2;
459
- (_a2 = this.logger) == null ? void 0 : _a2.warn(
460
- `[ServiceLocatorEventBus]#emit(): ${key}:${preEvent} rejected with`,
461
- result.reason
462
- );
463
- });
464
- });
465
- (_b = this.logger) == null ? void 0 : _b.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${event}`);
466
- const res = await Promise.allSettled(
467
- [...events.get(event) ?? []].map((listener) => listener(event))
468
- ).then((results) => {
469
- const res2 = results.filter((result) => result.status === "rejected").map((result) => {
470
- var _a2;
471
- (_a2 = this.logger) == null ? void 0 : _a2.warn(
472
- `[ServiceLocatorEventBus]#emit(): ${key}:${event} rejected with`,
473
- result.reason
474
- );
475
- return result;
476
- });
477
- if (res2.length > 0) {
478
- return Promise.reject(res2);
479
- }
480
- return results;
481
- });
482
- (_c = this.logger) == null ? void 0 : _c.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${postEvent}`);
483
- await Promise.allSettled(
484
- [...events.get(postEvent) ?? []].map((listener) => listener(postEvent))
485
- ).then((results) => {
486
- results.filter((result) => result.status === "rejected").forEach((result) => {
487
- var _a2;
488
- (_a2 = this.logger) == null ? void 0 : _a2.warn(
489
- `[ServiceLocatorEventBus]#emit(): ${key}:${postEvent} rejected with`,
490
- result.reason
491
- );
492
- });
493
- });
494
- return res;
495
- }
496
- };
497
-
498
- // packages/core/src/service-locator/service-locator-instance-holder.mts
499
- var ServiceLocatorInstanceHolderKind = /* @__PURE__ */ ((ServiceLocatorInstanceHolderKind2) => {
500
- ServiceLocatorInstanceHolderKind2["Instance"] = "instance";
501
- ServiceLocatorInstanceHolderKind2["Factory"] = "factory";
502
- ServiceLocatorInstanceHolderKind2["AbstractFactory"] = "abstractFactory";
503
- return ServiceLocatorInstanceHolderKind2;
504
- })(ServiceLocatorInstanceHolderKind || {});
505
- var ServiceLocatorInstanceHolderStatus = /* @__PURE__ */ ((ServiceLocatorInstanceHolderStatus2) => {
506
- ServiceLocatorInstanceHolderStatus2["Created"] = "created";
507
- ServiceLocatorInstanceHolderStatus2["Creating"] = "creating";
508
- ServiceLocatorInstanceHolderStatus2["Destroying"] = "destroying";
509
- return ServiceLocatorInstanceHolderStatus2;
510
- })(ServiceLocatorInstanceHolderStatus || {});
511
-
512
- // packages/core/src/service-locator/service-locator-manager.mts
513
- var ServiceLocatorManager = class {
514
- constructor(logger = null) {
515
- this.logger = logger;
516
- }
517
- instancesHolders = /* @__PURE__ */ new Map();
518
- get(name2) {
519
- var _a, _b, _c;
520
- const holder = this.instancesHolders.get(name2);
521
- if (holder) {
522
- if (holder.ttl !== Infinity) {
523
- const now = Date.now();
524
- if (now - holder.createdAt > holder.ttl) {
525
- (_a = this.logger) == null ? void 0 : _a.log(
526
- `[ServiceLocatorManager]#getInstanceHolder() TTL expired for ${holder.name}`
527
- );
528
- return [new InstanceExpired(holder.name), holder];
529
- }
530
- } else if (holder.status === "destroying" /* Destroying */) {
531
- (_b = this.logger) == null ? void 0 : _b.log(
532
- `[ServiceLocatorManager]#getInstanceHolder() Instance ${holder.name} is destroying`
533
- );
534
- return [new InstanceDestroying(holder.name), holder];
535
- }
536
- return [void 0, holder];
537
- } else {
538
- (_c = this.logger) == null ? void 0 : _c.log(
539
- `[ServiceLocatorManager]#getInstanceHolder() Instance ${name2} not found`
540
- );
541
- return [new InstanceNotFound(name2)];
542
- }
543
- }
544
- set(name2, holder) {
545
- this.instancesHolders.set(name2, holder);
546
- }
547
- has(name2) {
548
- const [error, holder] = this.get(name2);
549
- if (!error) {
550
- return [void 0, true];
551
- }
552
- if (["InstanceExpired" /* InstanceExpired */, "InstanceDestroying" /* InstanceDestroying */].includes(
553
- error.code
554
- )) {
555
- return [error];
556
- }
557
- return [void 0, !!holder];
558
- }
559
- delete(name2) {
560
- return this.instancesHolders.delete(name2);
561
- }
562
- filter(predicate) {
563
- return new Map(
564
- [...this.instancesHolders].filter(
565
- ([key, value]) => predicate(value, key)
566
- )
567
- );
568
- }
569
- };
570
-
571
- // packages/core/src/service-locator/service-locator.mts
572
- var ServiceLocator = class {
573
- constructor(logger = null) {
574
- this.logger = logger;
575
- this.eventBus = new ServiceLocatorEventBus(logger);
576
- this.manager = new ServiceLocatorManager(logger);
577
- }
578
- abstractFactories = /* @__PURE__ */ new Map();
579
- instanceFactories = /* @__PURE__ */ new Map();
580
- eventBus;
581
- manager;
582
- getEventBus() {
583
- return this.eventBus;
584
- }
585
- registerInstance(token, instance) {
586
- const instanceName = this.getInstanceIdentifier(token, void 0);
587
- this.manager.set(instanceName, {
588
- name: instanceName,
589
- instance,
590
- status: "created" /* Created */,
591
- kind: "instance" /* Instance */,
592
- createdAt: Date.now(),
593
- ttl: Infinity,
594
- deps: [],
595
- destroyListeners: [],
596
- effects: [],
597
- destroyPromise: null,
598
- creationPromise: null
599
- });
600
- this.eventBus.emit(instanceName, "create");
601
- }
602
- removeInstance(token) {
603
- const instanceName = this.getInstanceIdentifier(token, void 0);
604
- return this.invalidate(instanceName);
605
- }
606
- registerAbstractFactory(token, factory, type = "Singleton" /* Singleton */) {
607
- var _a;
608
- (_a = this.logger) == null ? void 0 : _a.log(
609
- `[ServiceLocator]#registerAbstractFactory(): Registering abstract factory for ${name}`
610
- );
611
- if (type === "Instance" /* Instance */) {
612
- this.instanceFactories.set(token, factory);
613
- this.abstractFactories.delete(token);
614
- } else {
615
- this.abstractFactories.set(token, factory);
616
- this.instanceFactories.delete(token);
617
- }
618
- }
619
- resolveTokenArgs(token, args) {
620
- var _a, _b;
621
- let realArgs = args;
622
- if (token instanceof BoundInjectionToken) {
623
- realArgs = token.value;
624
- } else if (token instanceof FactoryInjectionToken) {
625
- if (token.resolved) {
626
- realArgs = token.value;
627
- } else {
628
- return [new FactoryTokenNotResolved(token.name)];
629
- }
630
- }
631
- if (!token.schema) {
632
- return [void 0, realArgs];
633
- }
634
- const validatedArgs = (_a = token.schema) == null ? void 0 : _a.safeParse(realArgs);
635
- if (validatedArgs && !validatedArgs.success) {
636
- (_b = this.logger) == null ? void 0 : _b.error(
637
- `[ServiceLocator]#getInstance(): Error validating args for ${token.name.toString()}`,
638
- validatedArgs.error
639
- );
640
- return [new UnknownError(validatedArgs.error)];
641
- }
642
- return [void 0, validatedArgs == null ? void 0 : validatedArgs.data];
643
- }
644
- getInstanceIdentifier(token, args) {
645
- const [err, realArgs] = this.resolveTokenArgs(token, args);
646
- if (err) {
647
- throw err;
648
- }
649
- return this.makeInstanceName(token, realArgs);
650
- }
651
- async getInstance(token, args) {
652
- var _a, _b;
653
- const [err, realArgs] = this.resolveTokenArgs(token, args);
654
- if (err instanceof UnknownError) {
655
- throw err;
656
- } else if (err instanceof FactoryTokenNotResolved && token instanceof FactoryInjectionToken) {
657
- await token.resolve();
658
- return this.getInstance(token, args);
659
- }
660
- const instanceName = this.makeInstanceName(token, realArgs);
661
- const [error, holder] = this.manager.get(instanceName);
662
- if (!error) {
663
- if (holder.status === "creating" /* Creating */) {
664
- return holder.creationPromise;
665
- } else if (holder.status === "destroying" /* Destroying */) {
666
- return [new UnknownError("InstanceDestroying" /* InstanceDestroying */)];
667
- }
668
- return [void 0, holder.instance];
669
- }
670
- switch (error.code) {
671
- case "InstanceDestroying" /* InstanceDestroying */:
672
- (_a = this.logger) == null ? void 0 : _a.log(
673
- `[ServiceLocator]#getInstance() TTL expired for ${holder == null ? void 0 : holder.name}`
674
- );
675
- await (holder == null ? void 0 : holder.destroyPromise);
676
- return this.getInstance(token, args);
677
- case "InstanceExpired" /* InstanceExpired */:
678
- (_b = this.logger) == null ? void 0 : _b.log(
679
- `[ServiceLocator]#getInstance() TTL expired for ${holder == null ? void 0 : holder.name}`
680
- );
681
- await this.invalidate(instanceName);
682
- return this.getInstance(token, args);
683
- case "InstanceNotFound" /* InstanceNotFound */:
684
- break;
685
- default:
686
- return [error];
687
- }
688
- return this.createInstance(instanceName, token, realArgs);
689
- }
690
- async getOrThrowInstance(token, args) {
691
- const [error, instance] = await this.getInstance(token, args);
692
- if (error) {
693
- throw error;
694
- }
695
- return instance;
696
- }
697
- notifyListeners(name2, event = "create") {
698
- var _a;
699
- (_a = this.logger) == null ? void 0 : _a.log(
700
- `[ServiceLocator]#notifyListeners() Notifying listeners for ${name2} with event ${event}`
701
- );
702
- return this.eventBus.emit(name2, event);
703
- }
704
- async createInstance(instanceName, token, args) {
705
- var _a;
706
- (_a = this.logger) == null ? void 0 : _a.log(
707
- `[ServiceLocator]#createInstance() Creating instance for ${instanceName}`
708
- );
709
- let realToken = token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken ? token.token : token;
710
- if (this.abstractFactories.has(realToken) || this.instanceFactories.has(realToken)) {
711
- return this.createInstanceFromAbstractFactory(
712
- instanceName,
713
- realToken,
714
- args
715
- );
716
- } else {
717
- return [new FactoryNotFound(realToken.name.toString())];
718
- }
719
- }
720
- async createInstanceFromAbstractFactory(instanceName, token, args) {
721
- var _a;
722
- (_a = this.logger) == null ? void 0 : _a.log(
723
- `[ServiceLocator]#createInstanceFromAbstractFactory(): Creating instance for ${instanceName} from abstract factory`
724
- );
725
- const ctx = this.createContextForAbstractFactory(instanceName);
726
- let shouldStore = true;
727
- let abstractFactory = this.abstractFactories.get(token);
728
- if (!abstractFactory) {
729
- abstractFactory = this.instanceFactories.get(token);
730
- shouldStore = false;
731
- if (!abstractFactory) {
732
- return [new FactoryNotFound(token.name.toString())];
733
- }
734
- }
735
- const holder = {
736
- name: instanceName,
737
- instance: null,
738
- status: "creating" /* Creating */,
739
- kind: "abstractFactory" /* AbstractFactory */,
740
- // @ts-expect-error TS2322 This is correct type
741
- creationPromise: abstractFactory(ctx, args).then(async (instance) => {
742
- var _a2;
743
- holder.instance = instance;
744
- holder.status = "created" /* Created */;
745
- holder.deps = ctx.getDependencies();
746
- holder.destroyListeners = ctx.getDestroyListeners();
747
- holder.ttl = ctx.getTtl();
748
- if (holder.deps.length > 0) {
749
- (_a2 = this.logger) == null ? void 0 : _a2.log(
750
- `[ServiceLocator]#createInstanceFromAbstractFactory(): Adding subscriptions for ${instanceName} dependencies for their invalidations: ${holder.deps.join(
751
- ", "
752
- )}`
753
- );
754
- holder.deps.forEach((dependency) => {
755
- holder.destroyListeners.push(
756
- this.eventBus.on(
757
- dependency,
758
- "destroy",
759
- () => this.invalidate(instanceName)
760
- )
761
- );
762
- });
763
- }
764
- if (holder.ttl === 0 || !shouldStore) {
765
- await this.invalidate(instanceName);
766
- }
767
- await this.notifyListeners(instanceName);
768
- return [void 0, instance];
769
- }).catch((error) => {
770
- var _a2;
771
- (_a2 = this.logger) == null ? void 0 : _a2.error(
772
- `[ServiceLocator]#createInstanceFromAbstractFactory(): Error creating instance for ${instanceName}`,
773
- error
774
- );
775
- return [new UnknownError(error)];
776
- }),
777
- effects: [],
778
- deps: [],
779
- destroyListeners: [],
780
- createdAt: Date.now(),
781
- ttl: Infinity
782
- };
783
- if (shouldStore) {
784
- this.manager.set(instanceName, holder);
785
- }
786
- return holder.creationPromise;
787
- }
788
- createContextForAbstractFactory(instanceName) {
789
- const dependencies = /* @__PURE__ */ new Set();
790
- const destroyListeners = /* @__PURE__ */ new Set();
791
- const self = this;
792
- function invalidate(name2 = instanceName) {
793
- return self.invalidate(name2);
794
- }
795
- function addEffect(listener) {
796
- destroyListeners.add(listener);
797
- }
798
- let ttl = Infinity;
799
- function setTtl(value) {
800
- ttl = value;
801
- }
802
- function getTtl() {
803
- return ttl;
804
- }
805
- function on(key, event, listener) {
806
- destroyListeners.add(self.eventBus.on(key, event, listener));
807
- }
808
- return {
809
- // @ts-expect-error This is correct type
810
- async inject(token, args) {
811
- let injectionToken = token;
812
- if (typeof token === "function") {
813
- injectionToken = getInjectableToken(token);
814
- }
815
- if (injectionToken instanceof InjectionToken) {
816
- const validatedArgs = token.schema ? token.schema.safeParse(args) : void 0;
817
- const instanceName2 = self.makeInstanceName(token, validatedArgs);
818
- dependencies.add(instanceName2);
819
- return self.getOrThrowInstance(injectionToken, args);
820
- }
821
- throw new Error(
822
- `[ServiceLocator]#inject(): Invalid token type: ${typeof token}. Expected a class or an InjectionToken.`
823
- );
824
- },
825
- invalidate,
826
- eventBus: self.eventBus,
827
- on,
828
- getDependencies: () => Array.from(dependencies),
829
- addEffect,
830
- getDestroyListeners: () => Array.from(destroyListeners),
831
- setTtl,
832
- getTtl
833
- };
834
- }
835
- getSyncInstance(token, args) {
836
- const [err, realArgs] = this.resolveTokenArgs(token, args);
837
- if (err) {
838
- return null;
839
- }
840
- const instanceName = this.makeInstanceName(token, realArgs);
841
- const [error, holder] = this.manager.get(instanceName);
842
- if (error) {
843
- return null;
844
- }
845
- return holder.instance;
846
- }
847
- invalidate(service, round = 1) {
848
- var _a, _b, _c, _d, _e;
849
- (_a = this.logger) == null ? void 0 : _a.log(
850
- `[ServiceLocator]#invalidate(): Starting Invalidating process of ${service}`
851
- );
852
- const toInvalidate = this.manager.filter(
853
- (holder) => holder.name === service || holder.deps.includes(service)
854
- );
855
- const promises = [];
856
- for (const [key, holder] of toInvalidate.entries()) {
857
- if (holder.status === "destroying" /* Destroying */) {
858
- (_b = this.logger) == null ? void 0 : _b.trace(
859
- `[ServiceLocator]#invalidate(): ${key} is already being destroyed`
860
- );
861
- promises.push(holder.destroyPromise);
862
- continue;
863
- }
864
- if (holder.status === "creating" /* Creating */) {
865
- (_c = this.logger) == null ? void 0 : _c.trace(
866
- `[ServiceLocator]#invalidate(): ${key} is being created, waiting for creation to finish`
867
- );
868
- promises.push(
869
- (_d = holder.creationPromise) == null ? void 0 : _d.then(() => {
870
- var _a2;
871
- if (round > 3) {
872
- (_a2 = this.logger) == null ? void 0 : _a2.error(
873
- `[ServiceLocator]#invalidate(): ${key} creation is triggering a new invalidation round, but it is still not created`
874
- );
875
- return;
876
- }
877
- return this.invalidate(key, round + 1);
878
- })
879
- );
880
- continue;
881
- }
882
- holder.status = "destroying" /* Destroying */;
883
- (_e = this.logger) == null ? void 0 : _e.log(
884
- `[ServiceLocator]#invalidate(): Invalidating ${key} and notifying listeners`
885
- );
886
- holder.destroyPromise = Promise.all(
887
- holder.destroyListeners.map((listener) => listener())
888
- ).then(async () => {
889
- this.manager.delete(key);
890
- await this.notifyListeners(key, "destroy");
891
- });
892
- promises.push(holder.destroyPromise);
893
- }
894
- return Promise.all(promises);
895
- }
896
- async ready() {
897
- return Promise.all(
898
- Array.from(this.manager.filter(() => true)).map(([, holder]) => {
899
- var _a;
900
- if (holder.status === "creating" /* Creating */) {
901
- return (_a = holder.creationPromise) == null ? void 0 : _a.then(() => null);
902
- }
903
- if (holder.status === "destroying" /* Destroying */) {
904
- return holder.destroyPromise.then(() => null);
905
- }
906
- return Promise.resolve(null);
907
- })
908
- ).then(() => null);
909
- }
910
- makeInstanceName(token, args) {
911
- let stringifiedArgs = args ? ":" + JSON.stringify(args, (_, value) => {
912
- if (typeof value === "function") {
913
- return `function:${value.name}(${value.length})`;
914
- }
915
- if (typeof value === "symbol") {
916
- return value.toString();
917
- }
918
- return value;
919
- }).replaceAll(/"/g, "").replaceAll(/:/g, "=").replaceAll(/,/g, "|") : "";
920
- const { name: name2 } = token;
921
- if (typeof name2 === "function") {
922
- const className = name2.name;
923
- return `${className}(${token.id})${stringifiedArgs}`;
924
- } else if (typeof name2 === "symbol") {
925
- return `${name2.toString()}(${token.id})${stringifiedArgs}`;
926
- } else {
927
- return `${name2}(${token.id})${stringifiedArgs}`;
928
- }
929
- }
930
- };
931
-
932
- // packages/core/src/service-locator/injector.mts
933
- var serviceLocator = new ServiceLocator();
934
- function provideServiceLocator(locator) {
935
- const original = serviceLocator;
936
- serviceLocator = locator;
937
- return original;
938
- }
939
- function getServiceLocator() {
940
- if (!serviceLocator) {
941
- throw new Error(
942
- "[ServiceLocator] Service locator is not initialized. Please provide the service locator before using the @Injectable decorator."
943
- );
944
- }
945
- return serviceLocator;
946
- }
947
-
948
- // packages/core/src/service-locator/resolve-service.mts
949
- var import_common = require("@navios/common");
950
-
951
- // packages/core/src/service-locator/proxy-service-locator.mts
952
- var ProxyServiceLocator = class {
953
- constructor(serviceLocator2, ctx) {
954
- this.serviceLocator = serviceLocator2;
955
- this.ctx = ctx;
956
- }
957
- get abstractFactories() {
958
- return this.serviceLocator["abstractFactories"];
959
- }
960
- getEventBus() {
961
- return this.serviceLocator.getEventBus();
962
- }
963
- registerAbstractFactory(token, factory) {
964
- return this.serviceLocator.registerAbstractFactory(token, factory);
965
- }
966
- getInstance(token, args) {
967
- return this.ctx.inject(token, args).then(
968
- (instance) => {
969
- return [void 0, instance];
970
- },
971
- (error) => {
972
- return [error];
973
- }
974
- );
975
- }
976
- getOrThrowInstance(token, args) {
977
- return this.ctx.inject(token, args);
978
- }
979
- getSyncInstance(token, args) {
980
- return this.serviceLocator.getSyncInstance(token, args);
981
- }
982
- invalidate(service, round) {
983
- return this.serviceLocator.invalidate(service, round);
984
- }
985
- ready() {
986
- return this.serviceLocator.ready();
987
- }
988
- makeInstanceName(token, args) {
989
- return this.serviceLocator.makeInstanceName(token, args);
990
- }
991
- };
992
- function makeProxyServiceLocator(serviceLocator2, ctx) {
993
- return new ProxyServiceLocator(serviceLocator2, ctx);
994
- }
995
-
996
- // packages/core/src/service-locator/sync-injector.mts
997
- var promiseCollector = null;
998
- function syncInject(token, args) {
999
- let realToken = token;
1000
- if (!(token instanceof InjectionToken)) {
1001
- realToken = getInjectableToken(token);
1002
- }
1003
- const instance = getServiceLocator().getSyncInstance(realToken, args);
1004
- if (!instance) {
1005
- if (promiseCollector) {
1006
- const promise = getServiceLocator().getInstance(realToken, args);
1007
- promiseCollector(promise);
1008
- } else {
1009
- throw new Error(
1010
- `[ServiceLocator] No instance found for ${realToken.name.toString()}`
1011
- );
1012
- }
1013
- }
1014
- return instance;
1015
- }
1016
- function setPromiseCollector(collector) {
1017
- const original = promiseCollector;
1018
- promiseCollector = collector;
1019
- return original;
1020
- }
1021
-
1022
- // packages/core/src/service-locator/resolve-service.mts
1023
- async function resolveService(ctx, target, args = []) {
1024
- const proxyServiceLocator = makeProxyServiceLocator(getServiceLocator(), ctx);
1025
- let promises = [];
1026
- const promiseCollector2 = (promise) => {
1027
- promises.push(promise);
1028
- };
1029
- const originalPromiseCollector = setPromiseCollector(promiseCollector2);
1030
- const tryLoad = () => {
1031
- const original = provideServiceLocator(proxyServiceLocator);
1032
- let result = new target(...args);
1033
- provideServiceLocator(original);
1034
- return result;
1035
- };
1036
- let instance = tryLoad();
1037
- setPromiseCollector(originalPromiseCollector);
1038
- if (promises.length > 0) {
1039
- await Promise.all(promises);
1040
- promises = [];
1041
- instance = tryLoad();
1042
- }
1043
- if (promises.length > 0) {
1044
- console.error(`[ServiceLocator] ${target.name} has problem with it's definition.
1045
-
1046
- One or more of the dependencies are registered as a InjectableScope.Instance and are used with syncInject.
1047
-
1048
- Please use inject instead of syncInject to load those dependencies.`);
1049
- throw new import_common.NaviosException(
1050
- `[ServiceLocator] Service ${target.name} cannot be instantiated.`
1051
- );
1052
- }
1053
- return instance;
1054
- }
1055
-
1056
- // packages/core/src/service-locator/decorators/injectable.decorator.mts
1057
- var InjectableType = /* @__PURE__ */ ((InjectableType2) => {
1058
- InjectableType2["Class"] = "Class";
1059
- InjectableType2["Factory"] = "Factory";
1060
- return InjectableType2;
1061
- })(InjectableType || {});
1062
- var InjectableTokenMeta = Symbol("InjectableTokenMeta");
1063
- function Injectable({
1064
- scope = "Singleton" /* Singleton */,
1065
- type = "Class" /* Class */,
1066
- token
1067
- } = {}) {
1068
- return (target, context) => {
1069
- if (context.kind !== "class") {
1070
- throw new Error(
1071
- "[ServiceLocator] @Injectable decorator can only be used on classes."
1072
- );
1073
- }
1074
- let injectableToken = token ?? InjectionToken.create(target);
1075
- const locator = getServiceLocator();
1076
- if (type === "Class" /* Class */) {
1077
- locator.registerAbstractFactory(
1078
- injectableToken,
1079
- async (ctx) => resolveService(ctx, target),
1080
- scope
1081
- );
1082
- } else if (type === "Factory" /* Factory */) {
1083
- locator.registerAbstractFactory(
1084
- injectableToken,
1085
- async (ctx, args) => {
1086
- const builder = await resolveService(ctx, target);
1087
- if (typeof builder.create !== "function") {
1088
- throw new import_common2.NaviosException(
1089
- `[ServiceLocator] Factory ${target.name} does not implement the create method.`
1090
- );
1091
- }
1092
- return builder.create(ctx, args);
1093
- },
1094
- scope
1095
- );
1096
- }
1097
- target[InjectableTokenMeta] = injectableToken;
1098
- return target;
1099
- };
1100
- }
1101
-
1102
- // packages/core/src/service-locator/decorators/get-injectable-token.mts
1103
- function getInjectableToken(target) {
1104
- const token = target[InjectableTokenMeta];
1105
- if (!token) {
1106
- throw new Error(
1107
- `[ServiceLocator] Class ${target.name} is not decorated with @Injectable.`
1108
- );
1109
- }
1110
- return token;
1111
- }
1112
-
1113
- // packages/core/src/service-locator/event-emitter.mts
1114
- var EventEmitter = class {
1115
- listeners = /* @__PURE__ */ new Map();
1116
- on(event, listener) {
1117
- if (!this.listeners.has(event)) {
1118
- this.listeners.set(event, /* @__PURE__ */ new Set());
1119
- }
1120
- this.listeners.get(event).add(listener);
1121
- return () => {
1122
- this.off(event, listener);
1123
- };
1124
- }
1125
- off(event, listener) {
1126
- if (!this.listeners.has(event)) {
1127
- return;
1128
- }
1129
- this.listeners.get(event).delete(listener);
1130
- if (this.listeners.get(event).size === 0) {
1131
- this.listeners.delete(event);
1132
- }
1133
- }
1134
- once(event, listener) {
1135
- const off = this.on(event, (...args) => {
1136
- off();
1137
- listener(...args);
1138
- });
1139
- return off;
1140
- }
1141
- async emit(event, ...args) {
1142
- if (!this.listeners.has(event)) {
1143
- return;
1144
- }
1145
- return Promise.all(Array.from(this.listeners.get(event)).map((listener) => listener(...args)));
1146
- }
1147
- addChannel(ns, event, target) {
1148
- return this.on(event, (...args) => target.emit(ns, event, ...args));
1149
- }
1150
- };
1151
-
1152
- // packages/core/src/service-locator/inject.mts
1153
- function inject(token, args) {
1154
- let realToken = token;
1155
- if (!(token instanceof InjectionToken)) {
1156
- realToken = getInjectableToken(token);
1157
- }
1158
- return getServiceLocator().getOrThrowInstance(realToken, args);
1159
- }
1160
-
1161
- // packages/core/src/service-locator/override.mts
1162
- function override(token, target) {
1163
- const serviceLocator2 = getServiceLocator();
1164
- const originalDefinition = serviceLocator2["abstractFactories"].get(token);
1165
- serviceLocator2.registerAbstractFactory(token, async (ctx, args) => {
1166
- const builder = new target();
1167
- return builder.create(ctx, args);
1168
- });
1169
- return () => {
1170
- if (originalDefinition) {
1171
- serviceLocator2.registerAbstractFactory(token, originalDefinition);
1172
- }
1173
- };
1174
- }
493
+ var import_di11 = require("@navios/di");
1175
494
 
1176
495
  // packages/core/src/tokens/application.token.mts
496
+ var import_di4 = require("@navios/di");
1177
497
  var ApplicationInjectionToken = "ApplicationInjectionToken";
1178
- var Application = InjectionToken.create(
498
+ var Application = import_di4.InjectionToken.create(
1179
499
  ApplicationInjectionToken
1180
500
  );
1181
501
 
502
+ // packages/core/src/tokens/execution-context.token.mts
503
+ var import_di8 = require("@navios/di");
504
+
1182
505
  // packages/core/src/services/controller-adapter.service.mts
1183
- var import_common3 = require("@navios/common");
1184
- var import_zod2 = require("zod");
506
+ var import_di6 = require("@navios/di");
1185
507
 
1186
- // packages/core/src/metadata/endpoint.metadata.mts
508
+ // packages/core/src/metadata/handler.metadata.mts
1187
509
  var EndpointMetadataKey = Symbol("EndpointMetadataKey");
1188
- var EndpointType = /* @__PURE__ */ ((EndpointType2) => {
1189
- EndpointType2["Unknown"] = "unknown";
1190
- EndpointType2["Endpoint"] = "endpoint";
1191
- EndpointType2["Stream"] = "stream";
1192
- EndpointType2["Multipart"] = "multipart";
1193
- EndpointType2["Handler"] = "handler";
1194
- return EndpointType2;
1195
- })(EndpointType || {});
1196
510
  function getAllEndpointMetadata(context) {
1197
511
  if (context.metadata) {
1198
512
  const metadata = context.metadata[EndpointMetadataKey];
@@ -1219,9 +533,10 @@ function getEndpointMetadata(target, context) {
1219
533
  classMethod: target.name,
1220
534
  url: "",
1221
535
  successStatusCode: 200,
536
+ adapterToken: null,
1222
537
  headers: {},
1223
- type: "unknown" /* Unknown */,
1224
538
  httpMethod: "GET",
539
+ // @ts-expect-error We are using a generic type here
1225
540
  config: null,
1226
541
  guards: /* @__PURE__ */ new Set(),
1227
542
  customAttributes: /* @__PURE__ */ new Map()
@@ -1345,6 +660,9 @@ var ExecutionContext = class {
1345
660
  }
1346
661
  };
1347
662
 
663
+ // packages/core/src/services/guard-runner.service.mts
664
+ var import_di5 = require("@navios/di");
665
+
1348
666
  // packages/core/src/exceptions/http.exception.mts
1349
667
  var HttpException = class {
1350
668
  constructor(statusCode, response, error) {
@@ -1399,13 +717,13 @@ var ConflictException = class extends HttpException {
1399
717
  };
1400
718
 
1401
719
  // packages/core/src/services/guard-runner.service.mts
1402
- var _GuardRunnerService_decorators, _init;
1403
- _GuardRunnerService_decorators = [Injectable()];
720
+ var _GuardRunnerService_decorators, _init4;
721
+ _GuardRunnerService_decorators = [(0, import_di5.Injectable)()];
1404
722
  var GuardRunnerService = class {
1405
723
  async runGuards(allGuards, executionContext) {
1406
724
  let canActivate = true;
1407
725
  for (const guard of Array.from(allGuards).reverse()) {
1408
- const guardInstance = await inject(
726
+ const guardInstance = await (0, import_di5.inject)(
1409
727
  guard
1410
728
  );
1411
729
  if (!guardInstance.canActivate) {
@@ -1462,39 +780,59 @@ var GuardRunnerService = class {
1462
780
  return guards;
1463
781
  }
1464
782
  };
1465
- _init = __decoratorStart(null);
1466
- GuardRunnerService = __decorateElement(_init, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
1467
- __runInitializers(_init, 1, GuardRunnerService);
783
+ _init4 = __decoratorStart(null);
784
+ GuardRunnerService = __decorateElement(_init4, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
785
+ __runInitializers(_init4, 1, GuardRunnerService);
1468
786
 
1469
787
  // packages/core/src/services/controller-adapter.service.mts
1470
- var _ControllerAdapterService_decorators, _init2;
1471
- _ControllerAdapterService_decorators = [Injectable()];
788
+ var _ControllerAdapterService_decorators, _init5;
789
+ _ControllerAdapterService_decorators = [(0, import_di6.Injectable)()];
1472
790
  var _ControllerAdapterService = class _ControllerAdapterService {
1473
- guardRunner = syncInject(GuardRunnerService);
1474
- logger = syncInject(Logger, {
791
+ guardRunner = (0, import_di6.syncInject)(GuardRunnerService);
792
+ logger = (0, import_di6.syncInject)(Logger, {
1475
793
  context: _ControllerAdapterService.name
1476
794
  });
1477
- setupController(controller, instance, moduleMetadata) {
795
+ async setupController(controller, instance, moduleMetadata) {
796
+ var _a3, _b;
1478
797
  const controllerMetadata = extractControllerMetadata(controller);
1479
798
  for (const endpoint of controllerMetadata.endpoints) {
1480
- const { classMethod, url, httpMethod } = endpoint;
1481
- if (!url) {
799
+ const { classMethod, url, httpMethod, adapterToken } = endpoint;
800
+ if (!url || !adapterToken) {
1482
801
  throw new Error(
1483
802
  `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
1484
803
  );
1485
804
  }
805
+ const adapter = await (0, import_di6.inject)(
806
+ adapterToken
807
+ );
1486
808
  const executionContext = new ExecutionContext(
1487
809
  moduleMetadata,
1488
810
  controllerMetadata,
1489
811
  endpoint
1490
812
  );
1491
- instance.withTypeProvider().route({
1492
- method: httpMethod,
1493
- url: url.replaceAll("$", ":"),
1494
- schema: this.provideSchemaForConfig(endpoint),
1495
- preHandler: this.providePreHandler(executionContext),
1496
- handler: this.provideHandler(controller, executionContext, endpoint)
1497
- });
813
+ const hasSchema = ((_a3 = adapter.hasSchema) == null ? void 0 : _a3.call(adapter, endpoint)) ?? false;
814
+ if (hasSchema) {
815
+ instance.withTypeProvider().route({
816
+ method: httpMethod,
817
+ url: url.replaceAll("$", ":"),
818
+ schema: ((_b = adapter.provideSchema) == null ? void 0 : _b.call(adapter, endpoint)) ?? {},
819
+ preHandler: this.providePreHandler(executionContext),
820
+ handler: this.wrapHandler(
821
+ executionContext,
822
+ adapter.provideHandler(controller, executionContext, endpoint)
823
+ )
824
+ });
825
+ } else {
826
+ instance.route({
827
+ method: httpMethod,
828
+ url: url.replaceAll("$", ":"),
829
+ preHandler: this.providePreHandler(executionContext),
830
+ handler: this.wrapHandler(
831
+ executionContext,
832
+ adapter.provideHandler(controller, executionContext, endpoint)
833
+ )
834
+ });
835
+ }
1498
836
  this.logger.debug(
1499
837
  `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
1500
838
  );
@@ -1502,220 +840,53 @@ var _ControllerAdapterService = class _ControllerAdapterService {
1502
840
  }
1503
841
  providePreHandler(executionContext) {
1504
842
  const guards = this.guardRunner.makeContext(executionContext);
1505
- return guards.size > 0 ? async (request, reply) => {
1506
- getServiceLocator().registerInstance(Request, request);
1507
- getServiceLocator().registerInstance(Reply, reply);
1508
- getServiceLocator().registerInstance(
1509
- ExecutionContextToken,
1510
- executionContext
1511
- );
1512
- executionContext.provideRequest(request);
1513
- executionContext.provideReply(reply);
1514
- let canActivate = true;
1515
- try {
843
+ return guards.size > 0 ? this.wrapHandler(
844
+ executionContext,
845
+ async (request, reply) => {
846
+ let canActivate = true;
1516
847
  canActivate = await this.guardRunner.runGuards(
1517
848
  guards,
1518
849
  executionContext
1519
850
  );
1520
- } finally {
1521
- getServiceLocator().removeInstance(Request);
1522
- getServiceLocator().removeInstance(Reply);
1523
- getServiceLocator().removeInstance(ExecutionContextToken);
1524
- }
1525
- if (!canActivate) {
1526
- return reply;
1527
- }
1528
- } : void 0;
1529
- }
1530
- provideSchemaForConfig(endpointMetadata) {
1531
- if (!endpointMetadata.config) {
1532
- this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`);
1533
- return {};
1534
- }
1535
- const { querySchema, requestSchema, responseSchema } = endpointMetadata.config;
1536
- const schema = {};
1537
- if (querySchema) {
1538
- schema.querystring = querySchema;
1539
- }
1540
- if (requestSchema && endpointMetadata.type !== "multipart" /* Multipart */) {
1541
- schema.body = requestSchema;
1542
- }
1543
- if (responseSchema) {
1544
- schema.response = {
1545
- 200: responseSchema
1546
- };
1547
- }
1548
- return schema;
1549
- }
1550
- provideHandler(controller, executionContext, endpointMetadata) {
1551
- switch (endpointMetadata.type) {
1552
- case "unknown" /* Unknown */:
1553
- this.logger.error(
1554
- `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`
1555
- );
1556
- throw new import_common3.NaviosException("Unknown endpoint type");
1557
- case "endpoint" /* Endpoint */:
1558
- return this.provideHandlerForConfig(
1559
- controller,
1560
- executionContext,
1561
- endpointMetadata
1562
- );
1563
- case "stream" /* Stream */:
1564
- return this.provideHandlerForStream(
1565
- controller,
1566
- executionContext,
1567
- endpointMetadata
1568
- );
1569
- case "multipart" /* Multipart */:
1570
- return this.provideHandlerForMultipart(
1571
- controller,
1572
- executionContext,
1573
- endpointMetadata
1574
- );
1575
- case "handler" /* Handler */:
1576
- this.logger.error("Not implemented yet");
1577
- throw new import_common3.NaviosException("Not implemented yet");
1578
- }
1579
- }
1580
- provideHandlerForConfig(controller, executionContext, endpointMetadata) {
1581
- return async (request, reply) => {
1582
- getServiceLocator().registerInstance(Request, request);
1583
- getServiceLocator().registerInstance(Reply, reply);
1584
- getServiceLocator().registerInstance(
1585
- ExecutionContextToken,
1586
- executionContext
1587
- );
1588
- executionContext.provideRequest(request);
1589
- executionContext.provideReply(reply);
1590
- const controllerInstance = await inject(controller);
1591
- try {
1592
- const { query, params, body } = request;
1593
- const argument = {};
1594
- if (query && Object.keys(query).length > 0) {
1595
- argument.params = query;
1596
- }
1597
- if (params && Object.keys(params).length > 0) {
1598
- argument.urlParams = params;
1599
- }
1600
- if (body) {
1601
- argument.data = body;
1602
- }
1603
- const result = await controllerInstance[endpointMetadata.classMethod](argument);
1604
- reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
1605
- } finally {
1606
- getServiceLocator().removeInstance(Request);
1607
- getServiceLocator().removeInstance(Reply);
1608
- getServiceLocator().removeInstance(ExecutionContextToken);
1609
- }
1610
- };
1611
- }
1612
- provideHandlerForStream(controller, executionContext, endpointMetadata) {
1613
- return async (request, reply) => {
1614
- getServiceLocator().registerInstance(Request, request);
1615
- getServiceLocator().registerInstance(Reply, reply);
1616
- getServiceLocator().registerInstance(
1617
- ExecutionContextToken,
1618
- executionContext
1619
- );
1620
- executionContext.provideRequest(request);
1621
- executionContext.provideReply(reply);
1622
- const controllerInstance = await inject(controller);
1623
- try {
1624
- const { query, params, body } = request;
1625
- const argument = {};
1626
- if (query && Object.keys(query).length > 0) {
1627
- argument.params = query;
1628
- }
1629
- if (params && Object.keys(params).length > 0) {
1630
- argument.urlParams = params;
1631
- }
1632
- if (body) {
1633
- argument.data = body;
851
+ if (!canActivate) {
852
+ return reply;
1634
853
  }
1635
- await controllerInstance[endpointMetadata.classMethod](argument, reply);
1636
- } finally {
1637
- getServiceLocator().removeInstance(Request);
1638
- getServiceLocator().removeInstance(Reply);
1639
- getServiceLocator().removeInstance(ExecutionContextToken);
1640
854
  }
1641
- };
855
+ ) : void 0;
1642
856
  }
1643
- provideHandlerForMultipart(controller, executionContext, endpointMetadata) {
1644
- const config = endpointMetadata.config;
1645
- const requestSchema = config.requestSchema;
1646
- const shape = requestSchema._def.shape();
857
+ wrapHandler(executionContext, handler) {
858
+ const locator = (0, import_di6.getGlobalServiceLocator)();
1647
859
  return async (request, reply) => {
1648
- getServiceLocator().registerInstance(Request, request);
1649
- getServiceLocator().registerInstance(Reply, reply);
1650
- getServiceLocator().registerInstance(
1651
- ExecutionContextToken,
1652
- executionContext
1653
- );
860
+ locator.storeInstance(request, Request);
861
+ locator.storeInstance(reply, Reply);
862
+ locator.storeInstance(executionContext, ExecutionContextToken);
1654
863
  executionContext.provideRequest(request);
1655
864
  executionContext.provideReply(reply);
1656
- const controllerInstance = await inject(controller);
1657
865
  try {
1658
- const parts = request.parts();
1659
- const { query, params } = request;
1660
- const argument = {};
1661
- if (query && Object.keys(query).length > 0) {
1662
- argument.params = query;
1663
- }
1664
- if (params && Object.keys(params).length > 0) {
1665
- argument.urlParams = params;
1666
- }
1667
- const req = {};
1668
- for await (const part of parts) {
1669
- if (!shape[part.fieldname]) {
1670
- throw new import_common3.NaviosException(
1671
- `Invalid field name ${part.fieldname} for multipart request`
1672
- );
1673
- }
1674
- const schema = shape[part.fieldname];
1675
- if (part.type === "file") {
1676
- const file = new File([await part.toBuffer()], part.filename, {
1677
- type: part.mimetype
1678
- });
1679
- if (schema instanceof import_zod2.ZodArray) {
1680
- if (!req[part.fieldname]) {
1681
- req[part.fieldname] = [];
1682
- }
1683
- req[part.fieldname].push(file);
1684
- } else {
1685
- req[part.fieldname] = file;
1686
- }
1687
- } else {
1688
- if (schema instanceof import_zod2.ZodArray) {
1689
- if (!req[part.fieldname]) {
1690
- req[part.fieldname] = [];
1691
- }
1692
- req[part.fieldname].push(part.value);
1693
- } else {
1694
- req[part.fieldname] = part.value;
1695
- }
1696
- }
1697
- }
1698
- argument.data = requestSchema.parse(req);
1699
- const result = await controllerInstance[endpointMetadata.classMethod](argument);
1700
- reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
866
+ return await handler(request, reply);
1701
867
  } finally {
1702
- getServiceLocator().removeInstance(Request);
1703
- getServiceLocator().removeInstance(Reply);
1704
- getServiceLocator().removeInstance(ExecutionContextToken);
868
+ Promise.all([
869
+ locator.removeInstance(Request),
870
+ locator.removeInstance(Reply),
871
+ locator.removeInstance(ExecutionContextToken)
872
+ ]).catch((err) => {
873
+ this.logger.warn(`Error removing instances: ${err}`);
874
+ });
1705
875
  }
1706
876
  };
1707
877
  }
1708
878
  };
1709
- _init2 = __decoratorStart(null);
1710
- _ControllerAdapterService = __decorateElement(_init2, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
1711
- __runInitializers(_init2, 1, _ControllerAdapterService);
879
+ _init5 = __decoratorStart(null);
880
+ _ControllerAdapterService = __decorateElement(_init5, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
881
+ __runInitializers(_init5, 1, _ControllerAdapterService);
1712
882
  var ControllerAdapterService = _ControllerAdapterService;
1713
883
 
1714
884
  // packages/core/src/services/module-loader.service.mts
1715
- var _ModuleLoaderService_decorators, _init3;
1716
- _ModuleLoaderService_decorators = [Injectable()];
885
+ var import_di7 = require("@navios/di");
886
+ var _ModuleLoaderService_decorators, _init6;
887
+ _ModuleLoaderService_decorators = [(0, import_di7.Injectable)()];
1717
888
  var _ModuleLoaderService = class _ModuleLoaderService {
1718
- logger = syncInject(Logger, {
889
+ logger = (0, import_di7.syncInject)(Logger, {
1719
890
  context: _ModuleLoaderService.name
1720
891
  });
1721
892
  modulesMetadata = /* @__PURE__ */ new Map();
@@ -1743,7 +914,7 @@ var _ModuleLoaderService = class _ModuleLoaderService {
1743
914
  async (importedModule) => this.traverseModules(importedModule, metadata)
1744
915
  );
1745
916
  await Promise.all(loadingPromises);
1746
- const instance = await inject(module2);
917
+ const instance = await (0, import_di7.inject)(module2);
1747
918
  if (instance.onModuleInit) {
1748
919
  await instance.onModuleInit();
1749
920
  }
@@ -1774,24 +945,26 @@ var _ModuleLoaderService = class _ModuleLoaderService {
1774
945
  this.initialized = false;
1775
946
  }
1776
947
  };
1777
- _init3 = __decoratorStart(null);
1778
- _ModuleLoaderService = __decorateElement(_init3, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
1779
- __runInitializers(_init3, 1, _ModuleLoaderService);
948
+ _init6 = __decoratorStart(null);
949
+ _ModuleLoaderService = __decorateElement(_init6, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
950
+ __runInitializers(_init6, 1, _ModuleLoaderService);
1780
951
  var ModuleLoaderService = _ModuleLoaderService;
1781
952
 
1782
953
  // packages/core/src/tokens/execution-context.token.mts
1783
954
  var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
1784
- var ExecutionContextToken = InjectionToken.create(
955
+ var ExecutionContextToken = import_di8.InjectionToken.create(
1785
956
  ExecutionContextInjectionToken
1786
957
  );
1787
958
 
1788
959
  // packages/core/src/tokens/reply.token.mts
960
+ var import_di9 = require("@navios/di");
1789
961
  var ReplyInjectionToken = "ReplyInjectionToken";
1790
- var Reply = InjectionToken.create(ReplyInjectionToken);
962
+ var Reply = import_di9.InjectionToken.create(ReplyInjectionToken);
1791
963
 
1792
964
  // packages/core/src/tokens/request.token.mts
965
+ var import_di10 = require("@navios/di");
1793
966
  var RequestInjectionToken = "RequestInjectionToken";
1794
- var Request = InjectionToken.create(
967
+ var Request = import_di10.InjectionToken.create(
1795
968
  RequestInjectionToken
1796
969
  );
1797
970
 
@@ -1813,8 +986,8 @@ var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
1813
986
  day: "2-digit",
1814
987
  month: "2-digit"
1815
988
  });
1816
- var _ConsoleLogger_decorators, _init4;
1817
- _ConsoleLogger_decorators = [Injectable()];
989
+ var _ConsoleLogger_decorators, _init7;
990
+ _ConsoleLogger_decorators = [(0, import_di11.Injectable)()];
1818
991
  var _ConsoleLogger = class _ConsoleLogger {
1819
992
  /**
1820
993
  * The options of the logger.
@@ -1853,7 +1026,7 @@ var _ConsoleLogger = class _ConsoleLogger {
1853
1026
  this.originalContext = context;
1854
1027
  }
1855
1028
  if (opts == null ? void 0 : opts.requestId) {
1856
- const locator = getServiceLocator();
1029
+ const locator = (0, import_di11.getGlobalServiceLocator)();
1857
1030
  locator.getEventBus().on(locator.getInstanceIdentifier(Request, void 0), "create", () => {
1858
1031
  const request = locator.getSyncInstance(Request, void 0);
1859
1032
  this.requestId = (request == null ? void 0 : request.id) ?? null;
@@ -1949,8 +1122,8 @@ var _ConsoleLogger = class _ConsoleLogger {
1949
1122
  this.context = this.originalContext;
1950
1123
  }
1951
1124
  isLevelEnabled(level) {
1952
- var _a;
1953
- const logLevels = (_a = this.options) == null ? void 0 : _a.logLevels;
1125
+ var _a3;
1126
+ const logLevels = (_a3 = this.options) == null ? void 0 : _a3.logLevels;
1954
1127
  return isLogLevelEnabled(level, logLevels);
1955
1128
  }
1956
1129
  getTimestamp() {
@@ -2061,8 +1234,8 @@ var _ConsoleLogger = class _ConsoleLogger {
2061
1234
  `);
2062
1235
  }
2063
1236
  updateAndGetTimestampDiff() {
2064
- var _a;
2065
- const includeTimestamp = _ConsoleLogger.lastTimestampAt && ((_a = this.options) == null ? void 0 : _a.timestamp);
1237
+ var _a3;
1238
+ const includeTimestamp = _ConsoleLogger.lastTimestampAt && ((_a3 = this.options) == null ? void 0 : _a3.timestamp);
2066
1239
  const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
2067
1240
  _ConsoleLogger.lastTimestampAt = Date.now();
2068
1241
  return result;
@@ -2167,15 +1340,17 @@ var _ConsoleLogger = class _ConsoleLogger {
2167
1340
  }
2168
1341
  }
2169
1342
  };
2170
- _init4 = __decoratorStart(null);
2171
- _ConsoleLogger = __decorateElement(_init4, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
2172
- __runInitializers(_init4, 1, _ConsoleLogger);
1343
+ _init7 = __decoratorStart(null);
1344
+ _ConsoleLogger = __decorateElement(_init7, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
1345
+ __runInitializers(_init7, 1, _ConsoleLogger);
2173
1346
  var ConsoleLogger = _ConsoleLogger;
2174
1347
 
2175
1348
  // packages/core/src/logger/logger.factory.mts
2176
- var import_zod3 = require("zod");
1349
+ var import_di13 = require("@navios/di");
1350
+ var import_zod2 = require("zod");
2177
1351
 
2178
1352
  // packages/core/src/logger/logger.service.mts
1353
+ var import_di12 = require("@navios/di");
2179
1354
  var DEFAULT_LOGGER = new ConsoleLogger();
2180
1355
  var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
2181
1356
  year: "numeric",
@@ -2185,8 +1360,8 @@ var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
2185
1360
  day: "2-digit",
2186
1361
  month: "2-digit"
2187
1362
  });
2188
- var _LoggerInstance_decorators, _init5;
2189
- _LoggerInstance_decorators = [Injectable()];
1363
+ var _LoggerInstance_decorators, _init8;
1364
+ _LoggerInstance_decorators = [(0, import_di12.Injectable)()];
2190
1365
  var _LoggerInstance = class _LoggerInstance {
2191
1366
  constructor(context, options = {}) {
2192
1367
  this.context = context;
@@ -2207,69 +1382,69 @@ var _LoggerInstance = class _LoggerInstance {
2207
1382
  return _LoggerInstance.staticInstanceRef;
2208
1383
  }
2209
1384
  error(message, ...optionalParams) {
2210
- var _a;
1385
+ var _a3;
2211
1386
  optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
2212
1387
  this.context
2213
1388
  ) : optionalParams;
2214
- (_a = this.localInstance) == null ? void 0 : _a.error(message, ...optionalParams);
1389
+ (_a3 = this.localInstance) == null ? void 0 : _a3.error(message, ...optionalParams);
2215
1390
  }
2216
1391
  log(message, ...optionalParams) {
2217
- var _a;
1392
+ var _a3;
2218
1393
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2219
- (_a = this.localInstance) == null ? void 0 : _a.log(message, ...optionalParams);
1394
+ (_a3 = this.localInstance) == null ? void 0 : _a3.log(message, ...optionalParams);
2220
1395
  }
2221
1396
  warn(message, ...optionalParams) {
2222
- var _a;
1397
+ var _a3;
2223
1398
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2224
- (_a = this.localInstance) == null ? void 0 : _a.warn(message, ...optionalParams);
1399
+ (_a3 = this.localInstance) == null ? void 0 : _a3.warn(message, ...optionalParams);
2225
1400
  }
2226
1401
  debug(message, ...optionalParams) {
2227
- var _a, _b;
1402
+ var _a3, _b;
2228
1403
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2229
- (_b = (_a = this.localInstance) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1404
+ (_b = (_a3 = this.localInstance) == null ? void 0 : _a3.debug) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2230
1405
  }
2231
1406
  verbose(message, ...optionalParams) {
2232
- var _a, _b;
1407
+ var _a3, _b;
2233
1408
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2234
- (_b = (_a = this.localInstance) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1409
+ (_b = (_a3 = this.localInstance) == null ? void 0 : _a3.verbose) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2235
1410
  }
2236
1411
  fatal(message, ...optionalParams) {
2237
- var _a, _b;
1412
+ var _a3, _b;
2238
1413
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2239
- (_b = (_a = this.localInstance) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1414
+ (_b = (_a3 = this.localInstance) == null ? void 0 : _a3.fatal) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2240
1415
  }
2241
1416
  static error(message, ...optionalParams) {
2242
- var _a;
2243
- (_a = this.staticInstanceRef) == null ? void 0 : _a.error(message, ...optionalParams);
1417
+ var _a3;
1418
+ (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.error(message, ...optionalParams);
2244
1419
  }
2245
1420
  static log(message, ...optionalParams) {
2246
- var _a;
2247
- (_a = this.staticInstanceRef) == null ? void 0 : _a.log(message, ...optionalParams);
1421
+ var _a3;
1422
+ (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.log(message, ...optionalParams);
2248
1423
  }
2249
1424
  static warn(message, ...optionalParams) {
2250
- var _a;
2251
- (_a = this.staticInstanceRef) == null ? void 0 : _a.warn(message, ...optionalParams);
1425
+ var _a3;
1426
+ (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.warn(message, ...optionalParams);
2252
1427
  }
2253
1428
  static debug(message, ...optionalParams) {
2254
- var _a, _b;
2255
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1429
+ var _a3, _b;
1430
+ (_b = (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.debug) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2256
1431
  }
2257
1432
  static verbose(message, ...optionalParams) {
2258
- var _a, _b;
2259
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1433
+ var _a3, _b;
1434
+ (_b = (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.verbose) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2260
1435
  }
2261
1436
  static fatal(message, ...optionalParams) {
2262
- var _a, _b;
2263
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1437
+ var _a3, _b;
1438
+ (_b = (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.fatal) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2264
1439
  }
2265
1440
  static getTimestamp() {
2266
1441
  return dateTimeFormatter2.format(Date.now());
2267
1442
  }
2268
1443
  static overrideLogger(logger) {
2269
- var _a, _b;
1444
+ var _a3, _b;
2270
1445
  if (Array.isArray(logger)) {
2271
1446
  _LoggerInstance.logLevels = logger;
2272
- return (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.setLogLevels) == null ? void 0 : _b.call(_a, logger);
1447
+ return (_b = (_a3 = this.staticInstanceRef) == null ? void 0 : _a3.setLogLevels) == null ? void 0 : _b.call(_a3, logger);
2273
1448
  }
2274
1449
  if (isObject(logger)) {
2275
1450
  this.staticInstanceRef = logger;
@@ -2282,34 +1457,34 @@ var _LoggerInstance = class _LoggerInstance {
2282
1457
  return isLogLevelEnabled(level, logLevels);
2283
1458
  }
2284
1459
  registerLocalInstanceRef() {
2285
- var _a;
1460
+ var _a3;
2286
1461
  if (this.localInstanceRef) {
2287
1462
  return this.localInstanceRef;
2288
1463
  }
2289
1464
  this.localInstanceRef = new ConsoleLogger(this.context, {
2290
- timestamp: (_a = this.options) == null ? void 0 : _a.timestamp,
1465
+ timestamp: (_a3 = this.options) == null ? void 0 : _a3.timestamp,
2291
1466
  logLevels: _LoggerInstance.logLevels
2292
1467
  });
2293
1468
  return this.localInstanceRef;
2294
1469
  }
2295
1470
  };
2296
- _init5 = __decoratorStart(null);
2297
- _LoggerInstance = __decorateElement(_init5, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
2298
- __runInitializers(_init5, 1, _LoggerInstance);
1471
+ _init8 = __decoratorStart(null);
1472
+ _LoggerInstance = __decorateElement(_init8, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
1473
+ __runInitializers(_init8, 1, _LoggerInstance);
2299
1474
  var LoggerInstance = _LoggerInstance;
2300
1475
 
2301
1476
  // packages/core/src/logger/logger.factory.mts
2302
1477
  var LoggerInjectionToken = "LoggerInjectionToken";
2303
- var LoggerOptions = import_zod3.z.object({
2304
- context: import_zod3.z.string().optional(),
2305
- options: import_zod3.z.object({
2306
- timestamp: import_zod3.z.boolean().optional()
1478
+ var LoggerOptions = import_zod2.z.object({
1479
+ context: import_zod2.z.string().optional(),
1480
+ options: import_zod2.z.object({
1481
+ timestamp: import_zod2.z.boolean().optional()
2307
1482
  }).optional()
2308
1483
  }).optional();
2309
- var Logger = InjectionToken.create(LoggerInjectionToken, LoggerOptions);
2310
- var _LoggerFactory_decorators, _init6;
2311
- _LoggerFactory_decorators = [Injectable({
2312
- type: "Factory" /* Factory */,
1484
+ var Logger = import_di13.InjectionToken.create(LoggerInjectionToken, LoggerOptions);
1485
+ var _LoggerFactory_decorators, _init9;
1486
+ _LoggerFactory_decorators = [(0, import_di13.Injectable)({
1487
+ type: import_di13.InjectableType.Factory,
2313
1488
  token: Logger
2314
1489
  })];
2315
1490
  var LoggerFactory = class {
@@ -2317,9 +1492,9 @@ var LoggerFactory = class {
2317
1492
  return new LoggerInstance(args == null ? void 0 : args.context, args == null ? void 0 : args.options);
2318
1493
  }
2319
1494
  };
2320
- _init6 = __decoratorStart(null);
2321
- LoggerFactory = __decorateElement(_init6, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
2322
- __runInitializers(_init6, 1, LoggerFactory);
1495
+ _init9 = __decoratorStart(null);
1496
+ LoggerFactory = __decorateElement(_init9, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
1497
+ __runInitializers(_init9, 1, LoggerFactory);
2323
1498
 
2324
1499
  // packages/core/src/logger/pino-wrapper.mts
2325
1500
  var PinoWrapper = class _PinoWrapper {
@@ -2341,12 +1516,12 @@ var PinoWrapper = class _PinoWrapper {
2341
1516
  info() {
2342
1517
  }
2343
1518
  debug(message, ...optionalParams) {
2344
- var _a, _b;
2345
- (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1519
+ var _a3, _b;
1520
+ (_b = (_a3 = this.logger).debug) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2346
1521
  }
2347
1522
  trace(message, ...optionalParams) {
2348
- var _a, _b;
2349
- (_b = (_a = this.logger).verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1523
+ var _a3, _b;
1524
+ (_b = (_a3 = this.logger).verbose) == null ? void 0 : _b.call(_a3, message, ...optionalParams);
2350
1525
  }
2351
1526
  silent() {
2352
1527
  }
@@ -2374,7 +1549,7 @@ var PinoWrapper = class _PinoWrapper {
2374
1549
  };
2375
1550
 
2376
1551
  // packages/core/src/config/config.service.mts
2377
- var import_common4 = require("@navios/common");
1552
+ var import_common = require("@navios/common");
2378
1553
  var ConfigServiceInstance = class {
2379
1554
  constructor(config = {}, logger) {
2380
1555
  this.config = config;
@@ -2384,7 +1559,7 @@ var ConfigServiceInstance = class {
2384
1559
  return this.config;
2385
1560
  }
2386
1561
  get(key) {
2387
- var _a, _b;
1562
+ var _a3, _b;
2388
1563
  try {
2389
1564
  const parts = String(key).split(".");
2390
1565
  let value = this.config;
@@ -2396,8 +1571,8 @@ var ConfigServiceInstance = class {
2396
1571
  }
2397
1572
  return value ?? null;
2398
1573
  } catch (error) {
2399
- (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(
2400
- _a,
1574
+ (_b = (_a3 = this.logger).debug) == null ? void 0 : _b.call(
1575
+ _a3,
2401
1576
  `Failed to get config value for key ${String(key)}`,
2402
1577
  error
2403
1578
  );
@@ -2413,24 +1588,24 @@ var ConfigServiceInstance = class {
2413
1588
  if (value === null) {
2414
1589
  const message = errorMessage || `Configuration value for key "${String(key)}" is not defined`;
2415
1590
  this.logger.error(message);
2416
- throw new import_common4.NaviosException(message);
1591
+ throw new import_common.NaviosException(message);
2417
1592
  }
2418
1593
  return value;
2419
1594
  }
2420
1595
  };
2421
1596
 
2422
1597
  // packages/core/src/config/config.provider.mts
2423
- var ConfigProviderOptions = import_zod4.z.object({
2424
- load: import_zod4.z.function()
1598
+ var ConfigProviderOptions = import_zod3.z.object({
1599
+ load: import_zod3.z.function()
2425
1600
  });
2426
- var ConfigProvider = InjectionToken.create(ConfigServiceInstance, ConfigProviderOptions);
2427
- var _ConfigProviderFactory_decorators, _init7;
2428
- _ConfigProviderFactory_decorators = [Injectable({
1601
+ var ConfigProvider = import_di14.InjectionToken.create(ConfigServiceInstance, ConfigProviderOptions);
1602
+ var _ConfigProviderFactory_decorators, _init10;
1603
+ _ConfigProviderFactory_decorators = [(0, import_di14.Injectable)({
2429
1604
  token: ConfigProvider,
2430
- type: "Factory" /* Factory */
1605
+ type: import_di14.InjectableType.Factory
2431
1606
  })];
2432
1607
  var ConfigProviderFactory = class {
2433
- logger = syncInject(Logger, {
1608
+ logger = (0, import_di14.syncInject)(Logger, {
2434
1609
  context: "ConfigService"
2435
1610
  });
2436
1611
  async create(ctx, args) {
@@ -2438,21 +1613,25 @@ var ConfigProviderFactory = class {
2438
1613
  const logger = this.logger;
2439
1614
  try {
2440
1615
  const config = await load();
2441
- return new ConfigServiceInstance(config, logger);
1616
+ return new ConfigServiceInstance(
1617
+ config,
1618
+ logger
1619
+ );
2442
1620
  } catch (error) {
2443
1621
  logger.error("Error loading config", error);
2444
1622
  throw error;
2445
1623
  }
2446
1624
  }
2447
1625
  };
2448
- _init7 = __decoratorStart(null);
2449
- ConfigProviderFactory = __decorateElement(_init7, 0, "ConfigProviderFactory", _ConfigProviderFactory_decorators, ConfigProviderFactory);
2450
- __runInitializers(_init7, 1, ConfigProviderFactory);
1626
+ _init10 = __decoratorStart(null);
1627
+ ConfigProviderFactory = __decorateElement(_init10, 0, "ConfigProviderFactory", _ConfigProviderFactory_decorators, ConfigProviderFactory);
1628
+ __runInitializers(_init10, 1, ConfigProviderFactory);
2451
1629
  function provideConfig(options) {
2452
- return InjectionToken.bound(ConfigProvider, options);
1630
+ return import_di14.InjectionToken.bound(ConfigProvider, options);
2453
1631
  }
2454
1632
 
2455
1633
  // packages/core/src/decorators/controller.decorator.mts
1634
+ var import_di15 = require("@navios/di");
2456
1635
  function Controller({ guards } = {}) {
2457
1636
  return function(target, context) {
2458
1637
  if (context.kind !== "class") {
@@ -2460,7 +1639,7 @@ function Controller({ guards } = {}) {
2460
1639
  "[Navios] @Controller decorator can only be used on classes."
2461
1640
  );
2462
1641
  }
2463
- const token = InjectionToken.create(target);
1642
+ const token = import_di15.InjectionToken.create(target);
2464
1643
  if (context.metadata) {
2465
1644
  const controllerMetadata = getControllerMetadata(target, context);
2466
1645
  if (guards) {
@@ -2469,16 +1648,15 @@ function Controller({ guards } = {}) {
2469
1648
  }
2470
1649
  }
2471
1650
  }
2472
- return Injectable({
1651
+ return (0, import_di15.Injectable)({
2473
1652
  token,
2474
- type: "Class" /* Class */,
2475
- scope: "Instance" /* Instance */
1653
+ scope: import_di15.InjectableScope.Instance
2476
1654
  })(target, context);
2477
1655
  };
2478
1656
  }
2479
1657
 
2480
1658
  // packages/core/src/decorators/endpoint.decorator.mts
2481
- var import_zod5 = require("zod");
1659
+ var import_zod4 = require("zod");
2482
1660
  function Endpoint(endpoint) {
2483
1661
  return (target, context) => {
2484
1662
  if (typeof target !== "function") {
@@ -2493,14 +1671,17 @@ function Endpoint(endpoint) {
2493
1671
  }
2494
1672
  const config = endpoint.config;
2495
1673
  if (context.metadata) {
2496
- let endpointMetadata = getEndpointMetadata(target, context);
1674
+ let endpointMetadata = getEndpointMetadata(
1675
+ target,
1676
+ context
1677
+ );
2497
1678
  if (endpointMetadata.config && endpointMetadata.config.url) {
2498
1679
  throw new Error(
2499
1680
  `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2500
1681
  );
2501
1682
  }
2502
1683
  endpointMetadata.config = config;
2503
- endpointMetadata.type = "endpoint" /* Endpoint */;
1684
+ endpointMetadata.adapterToken = EndpointAdapterToken;
2504
1685
  endpointMetadata.classMethod = target.name;
2505
1686
  endpointMetadata.httpMethod = config.method;
2506
1687
  endpointMetadata.url = config.url;
@@ -2510,18 +1691,13 @@ function Endpoint(endpoint) {
2510
1691
  }
2511
1692
 
2512
1693
  // packages/core/src/decorators/header.decorator.mts
2513
- function Header(name2, value) {
1694
+ function Header(name, value) {
2514
1695
  return (target, context) => {
2515
1696
  if (context.kind !== "method") {
2516
1697
  throw new Error("[Navios] Header decorator can only be used on methods.");
2517
1698
  }
2518
1699
  const metadata = getEndpointMetadata(target, context);
2519
- if (metadata.type === "stream" /* Stream */) {
2520
- throw new Error(
2521
- "[Navios] HttpCode decorator cannot be used on stream endpoints."
2522
- );
2523
- }
2524
- metadata.headers[name2] = value;
1700
+ metadata.headers[name] = value;
2525
1701
  return target;
2526
1702
  };
2527
1703
  }
@@ -2535,49 +1711,42 @@ function HttpCode(code) {
2535
1711
  );
2536
1712
  }
2537
1713
  const metadata = getEndpointMetadata(target, context);
2538
- if (metadata.type === "stream" /* Stream */) {
2539
- throw new Error(
2540
- "[Navios] HttpCode decorator cannot be used on stream endpoints."
2541
- );
2542
- }
2543
1714
  metadata.successStatusCode = code;
2544
1715
  return target;
2545
1716
  };
2546
1717
  }
2547
1718
 
2548
1719
  // packages/core/src/decorators/module.decorator.mts
2549
- function Module(metadata) {
1720
+ var import_di16 = require("@navios/di");
1721
+ function Module({ controllers = [], imports = [], guards = [] } = {
1722
+ controllers: [],
1723
+ imports: [],
1724
+ guards: []
1725
+ }) {
2550
1726
  return (target, context) => {
2551
1727
  if (context.kind !== "class") {
2552
1728
  throw new Error("[Navios] @Module decorator can only be used on classes.");
2553
1729
  }
2554
- const token = InjectionToken.create(target);
1730
+ const token = import_di16.InjectionToken.create(target);
2555
1731
  const moduleMetadata = getModuleMetadata(target, context);
2556
- if (metadata.controllers) {
2557
- for (const controller of metadata.controllers) {
2558
- moduleMetadata.controllers.add(controller);
2559
- }
1732
+ for (const controller of controllers) {
1733
+ moduleMetadata.controllers.add(controller);
2560
1734
  }
2561
- if (metadata.imports) {
2562
- for (const importedModule of metadata.imports) {
2563
- moduleMetadata.imports.add(importedModule);
2564
- }
1735
+ for (const importedModule of imports) {
1736
+ moduleMetadata.imports.add(importedModule);
2565
1737
  }
2566
- if (metadata.guards) {
2567
- for (const guard of Array.from(metadata.guards).reverse()) {
2568
- moduleMetadata.guards.add(guard);
2569
- }
1738
+ for (const guard of Array.from(guards).reverse()) {
1739
+ moduleMetadata.guards.add(guard);
2570
1740
  }
2571
- return Injectable({
1741
+ return (0, import_di16.Injectable)({
2572
1742
  token,
2573
- type: "Class" /* Class */,
2574
- scope: "Singleton" /* Singleton */
1743
+ scope: import_di16.InjectableScope.Singleton
2575
1744
  })(target, context);
2576
1745
  };
2577
1746
  }
2578
1747
 
2579
1748
  // packages/core/src/decorators/multipart.decorator.mts
2580
- var import_zod6 = require("zod");
1749
+ var import_zod5 = require("zod");
2581
1750
  function Multipart(endpoint) {
2582
1751
  return (target, context) => {
2583
1752
  if (typeof target !== "function") {
@@ -2592,14 +1761,17 @@ function Multipart(endpoint) {
2592
1761
  }
2593
1762
  const config = endpoint.config;
2594
1763
  if (context.metadata) {
2595
- let endpointMetadata = getEndpointMetadata(target, context);
1764
+ let endpointMetadata = getEndpointMetadata(
1765
+ target,
1766
+ context
1767
+ );
2596
1768
  if (endpointMetadata.config && endpointMetadata.config.url) {
2597
1769
  throw new Error(
2598
1770
  `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2599
1771
  );
2600
1772
  }
2601
1773
  endpointMetadata.config = config;
2602
- endpointMetadata.type = "multipart" /* Multipart */;
1774
+ endpointMetadata.adapterToken = MultipartAdapterToken;
2603
1775
  endpointMetadata.classMethod = target.name;
2604
1776
  endpointMetadata.httpMethod = config.method;
2605
1777
  endpointMetadata.url = config.url;
@@ -2623,14 +1795,17 @@ function Stream(endpoint) {
2623
1795
  }
2624
1796
  const config = endpoint.config;
2625
1797
  if (context.metadata) {
2626
- let endpointMetadata = getEndpointMetadata(target, context);
1798
+ let endpointMetadata = getEndpointMetadata(
1799
+ target,
1800
+ context
1801
+ );
2627
1802
  if (endpointMetadata.config && endpointMetadata.config.url) {
2628
1803
  throw new Error(
2629
1804
  `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2630
1805
  );
2631
1806
  }
2632
1807
  endpointMetadata.config = config;
2633
- endpointMetadata.type = "stream" /* Stream */;
1808
+ endpointMetadata.adapterToken = StreamAdapterToken;
2634
1809
  endpointMetadata.classMethod = target.name;
2635
1810
  endpointMetadata.httpMethod = config.method;
2636
1811
  endpointMetadata.url = config.url;
@@ -2722,16 +1897,17 @@ var AttributeFactory = class {
2722
1897
  };
2723
1898
 
2724
1899
  // packages/core/src/navios.application.mts
1900
+ var import_di17 = require("@navios/di");
2725
1901
  var import_cors = __toESM(require("@fastify/cors"), 1);
2726
1902
  var import_multipart = __toESM(require("@fastify/multipart"), 1);
2727
1903
  var import_fastify = require("fastify");
2728
1904
  var import_fastify_type_provider_zod = require("fastify-type-provider-zod");
2729
- var _NaviosApplication_decorators, _init8;
2730
- _NaviosApplication_decorators = [Injectable()];
1905
+ var _NaviosApplication_decorators, _init11;
1906
+ _NaviosApplication_decorators = [(0, import_di17.Injectable)()];
2731
1907
  var _NaviosApplication = class _NaviosApplication {
2732
- moduleLoader = syncInject(ModuleLoaderService);
2733
- controllerAdapter = syncInject(ControllerAdapterService);
2734
- logger = syncInject(Logger, {
1908
+ moduleLoader = (0, import_di17.syncInject)(ModuleLoaderService);
1909
+ controllerAdapter = (0, import_di17.syncInject)(ControllerAdapterService);
1910
+ logger = (0, import_di17.syncInject)(Logger, {
2735
1911
  context: _NaviosApplication.name
2736
1912
  });
2737
1913
  server = null;
@@ -2752,7 +1928,7 @@ var _NaviosApplication = class _NaviosApplication {
2752
1928
  await this.moduleLoader.loadModules(this.appModule);
2753
1929
  this.server = await this.getFastifyInstance(this.options);
2754
1930
  this.configureFastifyInstance(this.server);
2755
- getServiceLocator().registerInstance(Application, this.server);
1931
+ (0, import_di17.getGlobalServiceLocator)().storeInstance(this.server, Application);
2756
1932
  this.server.setValidatorCompiler(import_fastify_type_provider_zod.validatorCompiler);
2757
1933
  this.server.setSerializerCompiler(import_fastify_type_provider_zod.serializerCompiler);
2758
1934
  if (this.corsOptions) {
@@ -2776,7 +1952,7 @@ var _NaviosApplication = class _NaviosApplication {
2776
1952
  }
2777
1953
  } else {
2778
1954
  fastifyOptions.loggerInstance = new PinoWrapper(
2779
- await inject(Logger, {
1955
+ await (0, import_di17.inject)(Logger, {
2780
1956
  context: "FastifyAdapter"
2781
1957
  })
2782
1958
  );
@@ -2786,7 +1962,7 @@ var _NaviosApplication = class _NaviosApplication {
2786
1962
  return (0, import_fastify.fastify)({
2787
1963
  ...options,
2788
1964
  loggerInstance: new PinoWrapper(
2789
- await inject(Logger, {
1965
+ await (0, import_di17.inject)(Logger, {
2790
1966
  context: "FastifyAdapter"
2791
1967
  })
2792
1968
  )
@@ -2818,7 +1994,7 @@ var _NaviosApplication = class _NaviosApplication {
2818
1994
  message: "Not Found",
2819
1995
  error: "NotFound"
2820
1996
  };
2821
- this.logger.error(`Route not found: ${req.url}`);
1997
+ this.logger.error(`Route not found: [${req.method}] ${req.url}`);
2822
1998
  return reply.status(404).send(response);
2823
1999
  });
2824
2000
  }
@@ -2839,15 +2015,14 @@ var _NaviosApplication = class _NaviosApplication {
2839
2015
  }
2840
2016
  promises.push(
2841
2017
  this.server.register(
2842
- (instance, opts, done) => {
2018
+ async (instance, opts) => {
2843
2019
  for (const controller of moduleMetadata.controllers) {
2844
- this.controllerAdapter.setupController(
2020
+ await this.controllerAdapter.setupController(
2845
2021
  controller,
2846
2022
  instance,
2847
2023
  moduleMetadata
2848
2024
  );
2849
2025
  }
2850
- done();
2851
2026
  },
2852
2027
  {
2853
2028
  prefix: this.globalPrefix ?? ""
@@ -2892,15 +2067,16 @@ var _NaviosApplication = class _NaviosApplication {
2892
2067
  await this.dispose();
2893
2068
  }
2894
2069
  };
2895
- _init8 = __decoratorStart(null);
2896
- _NaviosApplication = __decorateElement(_init8, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
2897
- __runInitializers(_init8, 1, _NaviosApplication);
2070
+ _init11 = __decoratorStart(null);
2071
+ _NaviosApplication = __decorateElement(_init11, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
2072
+ __runInitializers(_init11, 1, _NaviosApplication);
2898
2073
  var NaviosApplication = _NaviosApplication;
2899
2074
 
2900
2075
  // packages/core/src/navios.factory.mts
2076
+ var import_di18 = require("@navios/di");
2901
2077
  var NaviosFactory = class {
2902
2078
  static async create(appModule, options = {}) {
2903
- const app = await inject(NaviosApplication);
2079
+ const app = await (0, import_di18.inject)(NaviosApplication);
2904
2080
  this.registerLoggerConfiguration(options);
2905
2081
  app.setup(appModule, options);
2906
2082
  return app;
@@ -2920,7 +2096,6 @@ var NaviosFactory = class {
2920
2096
  Application,
2921
2097
  AttributeFactory,
2922
2098
  BadRequestException,
2923
- BoundInjectionToken,
2924
2099
  ConfigProvider,
2925
2100
  ConfigProviderFactory,
2926
2101
  ConfigProviderOptions,
@@ -2931,29 +2106,17 @@ var NaviosFactory = class {
2931
2106
  ControllerAdapterService,
2932
2107
  ControllerMetadataKey,
2933
2108
  Endpoint,
2109
+ EndpointAdapterService,
2110
+ EndpointAdapterToken,
2934
2111
  EndpointMetadataKey,
2935
- EndpointType,
2936
- ErrorsEnum,
2937
- EventEmitter,
2938
2112
  ExecutionContext,
2939
2113
  ExecutionContextInjectionToken,
2940
2114
  ExecutionContextToken,
2941
- FactoryInjectionToken,
2942
- FactoryNotFound,
2943
- FactoryTokenNotResolved,
2944
2115
  ForbiddenException,
2945
2116
  GuardRunnerService,
2946
2117
  Header,
2947
2118
  HttpCode,
2948
2119
  HttpException,
2949
- Injectable,
2950
- InjectableScope,
2951
- InjectableTokenMeta,
2952
- InjectableType,
2953
- InjectionToken,
2954
- InstanceDestroying,
2955
- InstanceExpired,
2956
- InstanceNotFound,
2957
2120
  InternalServerErrorException,
2958
2121
  LOG_LEVELS,
2959
2122
  Logger,
@@ -2965,20 +2128,18 @@ var NaviosFactory = class {
2965
2128
  ModuleLoaderService,
2966
2129
  ModuleMetadataKey,
2967
2130
  Multipart,
2131
+ MultipartAdapterService,
2132
+ MultipartAdapterToken,
2968
2133
  NaviosApplication,
2969
2134
  NaviosFactory,
2970
2135
  NotFoundException,
2971
2136
  PinoWrapper,
2972
2137
  Reply,
2973
2138
  Request,
2974
- ServiceLocator,
2975
- ServiceLocatorEventBus,
2976
- ServiceLocatorInstanceHolderKind,
2977
- ServiceLocatorInstanceHolderStatus,
2978
- ServiceLocatorManager,
2979
2139
  Stream,
2140
+ StreamAdapterService,
2141
+ StreamAdapterToken,
2980
2142
  UnauthorizedException,
2981
- UnknownError,
2982
2143
  UseGuards,
2983
2144
  addLeadingSlash,
2984
2145
  clc,
@@ -2990,12 +2151,9 @@ var NaviosFactory = class {
2990
2151
  getAllEndpointMetadata,
2991
2152
  getControllerMetadata,
2992
2153
  getEndpointMetadata,
2993
- getInjectableToken,
2994
2154
  getModuleMetadata,
2995
- getServiceLocator,
2996
2155
  hasControllerMetadata,
2997
2156
  hasModuleMetadata,
2998
- inject,
2999
2157
  isConstructor,
3000
2158
  isEmpty,
3001
2159
  isFunction,
@@ -3009,12 +2167,8 @@ var NaviosFactory = class {
3009
2167
  isSymbol,
3010
2168
  isUndefined,
3011
2169
  normalizePath,
3012
- override,
3013
2170
  provideConfig,
3014
- provideServiceLocator,
3015
- resolveService,
3016
- setPromiseCollector,
3017
2171
  stripEndSlash,
3018
- syncInject,
3019
- yellow
2172
+ yellow,
2173
+ ...require("@navios/di")
3020
2174
  });