@navios/core 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +95 -2
  2. package/docs/README.md +310 -3
  3. package/docs/adapters.md +308 -0
  4. package/docs/application-setup.md +524 -0
  5. package/docs/attributes.md +689 -0
  6. package/docs/controllers.md +373 -0
  7. package/docs/endpoints.md +444 -0
  8. package/docs/exceptions.md +316 -0
  9. package/docs/guards.md +550 -0
  10. package/docs/modules.md +377 -0
  11. package/docs/quick-start.md +295 -0
  12. package/docs/services.md +427 -0
  13. package/docs/testing.md +704 -0
  14. package/lib/_tsup-dts-rollup.d.mts +310 -239
  15. package/lib/_tsup-dts-rollup.d.ts +310 -239
  16. package/lib/index.d.mts +51 -28
  17. package/lib/index.d.ts +51 -28
  18. package/lib/index.js +633 -1072
  19. package/lib/index.js.map +1 -1
  20. package/lib/index.mjs +631 -1064
  21. package/lib/index.mjs.map +1 -1
  22. package/package.json +5 -9
  23. package/project.json +9 -1
  24. package/src/__tests__/config.service.spec.mts +11 -9
  25. package/src/__tests__/controller.spec.mts +0 -1
  26. package/src/config/config.service.mts +2 -2
  27. package/src/decorators/controller.decorator.mts +1 -1
  28. package/src/decorators/endpoint.decorator.mts +2 -2
  29. package/src/decorators/header.decorator.mts +1 -1
  30. package/src/decorators/multipart.decorator.mts +1 -2
  31. package/src/decorators/stream.decorator.mts +2 -3
  32. package/src/factories/endpoint-adapter.factory.mts +21 -0
  33. package/src/factories/http-adapter.factory.mts +20 -0
  34. package/src/factories/index.mts +6 -0
  35. package/src/factories/multipart-adapter.factory.mts +21 -0
  36. package/src/factories/reply.factory.mts +21 -0
  37. package/src/factories/request.factory.mts +21 -0
  38. package/src/factories/stream-adapter.factory.mts +20 -0
  39. package/src/index.mts +1 -1
  40. package/src/interfaces/abstract-execution-context.inteface.mts +13 -0
  41. package/src/interfaces/abstract-http-adapter.interface.mts +20 -0
  42. package/src/interfaces/abstract-http-cors-options.interface.mts +59 -0
  43. package/src/interfaces/abstract-http-handler-adapter.interface.mts +13 -0
  44. package/src/interfaces/abstract-http-listen-options.interface.mts +4 -0
  45. package/src/interfaces/can-activate.mts +4 -2
  46. package/src/interfaces/http-header.mts +18 -0
  47. package/src/interfaces/index.mts +6 -0
  48. package/src/logger/console-logger.service.mts +28 -44
  49. package/src/logger/index.mts +1 -2
  50. package/src/logger/logger.service.mts +9 -128
  51. package/src/logger/logger.tokens.mts +21 -0
  52. package/src/metadata/handler.metadata.mts +7 -5
  53. package/src/navios.application.mts +65 -172
  54. package/src/navios.environment.mts +30 -0
  55. package/src/navios.factory.mts +53 -12
  56. package/src/services/guard-runner.service.mts +19 -9
  57. package/src/services/index.mts +0 -2
  58. package/src/services/module-loader.service.mts +4 -3
  59. package/src/tokens/endpoint-adapter.token.mts +8 -0
  60. package/src/tokens/execution-context.token.mts +2 -2
  61. package/src/tokens/http-adapter.token.mts +8 -0
  62. package/src/tokens/index.mts +4 -1
  63. package/src/tokens/multipart-adapter.token.mts +8 -0
  64. package/src/tokens/reply.token.mts +1 -5
  65. package/src/tokens/request.token.mts +1 -7
  66. package/src/tokens/stream-adapter.token.mts +8 -0
  67. package/docs/recipes/prisma.md +0 -60
  68. package/e2e/endpoints/get.spec.mts +0 -97
  69. package/e2e/endpoints/post.spec.mts +0 -113
  70. package/examples/simple-test/api/index.mts +0 -64
  71. package/examples/simple-test/config/config.service.mts +0 -14
  72. package/examples/simple-test/config/configuration.mts +0 -7
  73. package/examples/simple-test/index.mts +0 -16
  74. package/examples/simple-test/src/acl/acl-modern.guard.mts +0 -15
  75. package/examples/simple-test/src/acl/acl.guard.mts +0 -14
  76. package/examples/simple-test/src/acl/app.guard.mts +0 -27
  77. package/examples/simple-test/src/acl/one-more.guard.mts +0 -15
  78. package/examples/simple-test/src/acl/public.attribute.mts +0 -21
  79. package/examples/simple-test/src/app.module.mts +0 -9
  80. package/examples/simple-test/src/user/user.controller.mts +0 -72
  81. package/examples/simple-test/src/user/user.module.mts +0 -14
  82. package/examples/simple-test/src/user/user.service.mts +0 -14
  83. package/src/adapters/endpoint-adapter.service.mts +0 -72
  84. package/src/adapters/handler-adapter.interface.mts +0 -21
  85. package/src/adapters/index.mts +0 -4
  86. package/src/adapters/multipart-adapter.service.mts +0 -135
  87. package/src/adapters/stream-adapter.service.mts +0 -91
  88. package/src/logger/logger.factory.mts +0 -36
  89. package/src/logger/pino-wrapper.mts +0 -64
  90. package/src/services/controller-adapter.service.mts +0 -124
  91. package/src/services/execution-context.mts +0 -54
  92. package/src/tokens/application.token.mts +0 -9
package/lib/index.mjs CHANGED
@@ -1,13 +1,9 @@
1
- import { InjectionToken, Injectable, InjectableType, getGlobalServiceLocator, inject, syncInject, InjectableScope } from '@navios/di';
1
+ import { InjectionToken, Injectable, Factory, InjectableScope, inject, Container, InjectableType } from '@navios/di';
2
2
  export * from '@navios/di';
3
- import { z, ZodOptional, ZodArray, ZodObject } from 'zod/v4';
4
3
  import { env } from 'process';
4
+ import z, { z as z$1 } from 'zod/v4';
5
5
  import { NaviosException } from '@navios/builder';
6
6
  import { inspect } from 'util';
7
- import cors from '@fastify/cors';
8
- import multipart from '@fastify/multipart';
9
- import { fastify } from 'fastify';
10
- import { validatorCompiler, serializerCompiler } from 'fastify-type-provider-zod';
11
7
 
12
8
  var __create = Object.create;
13
9
  var __defProp = Object.defineProperty;
@@ -18,7 +14,7 @@ var __typeError = (msg) => {
18
14
  };
19
15
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
20
16
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
21
- var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
17
+ var __decoratorStart = (base) => [, , , __create(null)];
22
18
  var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
23
19
  var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
24
20
  var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
@@ -40,223 +36,6 @@ var __decorateElement = (array, flags, name, decorators, target, extra) => {
40
36
  }
41
37
  return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
42
38
  };
43
- var StreamAdapterToken = InjectionToken.create(
44
- Symbol.for("StreamAdapterService")
45
- );
46
- var _StreamAdapterService_decorators, _init;
47
- _StreamAdapterService_decorators = [Injectable({
48
- token: StreamAdapterToken
49
- })];
50
- var StreamAdapterService = class {
51
- hasSchema(handlerMetadata) {
52
- const config = handlerMetadata.config;
53
- return !!config.requestSchema || !!config.querySchema;
54
- }
55
- prepareArguments(handlerMetadata) {
56
- const config = handlerMetadata.config;
57
- const getters = [];
58
- if (config.querySchema) {
59
- getters.push((target, request) => {
60
- target.params = request.query;
61
- });
62
- }
63
- if (config.requestSchema) {
64
- getters.push((target, request) => {
65
- target.data = request.body;
66
- });
67
- }
68
- if (config.url.includes("$")) {
69
- getters.push((target, request) => {
70
- target.urlParams = request.params;
71
- });
72
- }
73
- return getters;
74
- }
75
- provideHandler(controller, executionContext, handlerMetadata) {
76
- const getters = this.prepareArguments(handlerMetadata);
77
- const formatArguments = async (request) => {
78
- const argument = {};
79
- const promises = [];
80
- for (const getter of getters) {
81
- const res = getter(argument, request);
82
- if (res instanceof Promise) {
83
- promises.push(res);
84
- }
85
- }
86
- await Promise.all(promises);
87
- return argument;
88
- };
89
- return async function(request, reply) {
90
- const controllerInstance = await inject(controller);
91
- const argument = await formatArguments(request);
92
- await controllerInstance[handlerMetadata.classMethod](argument, reply);
93
- };
94
- }
95
- provideSchema(handlerMetadata) {
96
- const schema = {};
97
- const { querySchema, requestSchema } = handlerMetadata.config;
98
- if (querySchema) {
99
- schema.querystring = querySchema;
100
- }
101
- if (requestSchema) {
102
- schema.body = requestSchema;
103
- }
104
- return schema;
105
- }
106
- };
107
- _init = __decoratorStart(null);
108
- StreamAdapterService = __decorateElement(_init, 0, "StreamAdapterService", _StreamAdapterService_decorators, StreamAdapterService);
109
- __runInitializers(_init, 1, StreamAdapterService);
110
-
111
- // src/adapters/endpoint-adapter.service.mts
112
- var EndpointAdapterToken = InjectionToken.create(
113
- Symbol.for("EndpointAdapterService")
114
- );
115
- var _EndpointAdapterService_decorators, _init2, _a;
116
- _EndpointAdapterService_decorators = [Injectable({
117
- token: EndpointAdapterToken
118
- })];
119
- var EndpointAdapterService = class extends (_a = StreamAdapterService) {
120
- hasSchema(handlerMetadata) {
121
- const config = handlerMetadata.config;
122
- return super.hasSchema(handlerMetadata) || !!config.responseSchema;
123
- }
124
- provideSchema(handlerMetadata) {
125
- const config = handlerMetadata.config;
126
- const schema = super.provideSchema(handlerMetadata);
127
- if (config.responseSchema) {
128
- schema.response = {
129
- 200: config.responseSchema
130
- };
131
- }
132
- return schema;
133
- }
134
- provideHandler(controller, executionContext, handlerMetadata) {
135
- const getters = this.prepareArguments(handlerMetadata);
136
- const formatArguments = async (request) => {
137
- const argument = {};
138
- const promises = [];
139
- for (const getter of getters) {
140
- const res = getter(argument, request);
141
- if (res instanceof Promise) {
142
- promises.push(res);
143
- }
144
- }
145
- await Promise.all(promises);
146
- return argument;
147
- };
148
- return async function(request, reply) {
149
- const controllerInstance = await inject(controller);
150
- const argument = await formatArguments(request);
151
- const result = await controllerInstance[handlerMetadata.classMethod](argument);
152
- reply.status(handlerMetadata.successStatusCode).headers(handlerMetadata.headers).send(result);
153
- };
154
- }
155
- };
156
- _init2 = __decoratorStart(_a);
157
- EndpointAdapterService = __decorateElement(_init2, 0, "EndpointAdapterService", _EndpointAdapterService_decorators, EndpointAdapterService);
158
- __runInitializers(_init2, 1, EndpointAdapterService);
159
- var MultipartAdapterToken = InjectionToken.create(
160
- Symbol.for("MultipartAdapterService")
161
- );
162
- var _MultipartAdapterService_decorators, _init3, _a2;
163
- _MultipartAdapterService_decorators = [Injectable({
164
- token: MultipartAdapterToken
165
- })];
166
- var MultipartAdapterService = class extends (_a2 = EndpointAdapterService) {
167
- prepareArguments(handlerMetadata) {
168
- const config = handlerMetadata.config;
169
- const getters = [];
170
- if (config.querySchema) {
171
- getters.push((target, request) => {
172
- target.params = request.query;
173
- });
174
- }
175
- if (config.url.includes("$")) {
176
- getters.push((target, request) => {
177
- target.urlParams = request.params;
178
- });
179
- }
180
- const requestSchema = config.requestSchema;
181
- const shape = requestSchema._zod.def.shape;
182
- const structure = this.analyzeSchema(shape);
183
- getters.push(async (target, request) => {
184
- const req = {};
185
- for await (const part of request.parts()) {
186
- await this.populateRequest(structure, part, req);
187
- }
188
- target.data = requestSchema.parse(req);
189
- });
190
- return getters;
191
- }
192
- async populateRequest(structure, part, req) {
193
- const { isArray, isObject: isObject2 } = structure[part.fieldname] ?? {};
194
- if (isArray && !req[part.fieldname]) {
195
- req[part.fieldname] = [];
196
- }
197
- let value;
198
- if (part.type === "file") {
199
- value = new File(
200
- [await part.toBuffer()],
201
- part.filename,
202
- {
203
- type: part.mimetype
204
- }
205
- );
206
- } else {
207
- value = part.value;
208
- if (isObject2 && typeof value === "string") {
209
- value = JSON.parse(value);
210
- }
211
- }
212
- if (isArray) {
213
- req[part.fieldname].push(value);
214
- } else {
215
- req[part.fieldname] = value;
216
- }
217
- }
218
- analyzeSchema(shape) {
219
- return Object.keys(shape).reduce(
220
- (target, key) => {
221
- let schema = shape[key];
222
- const isOptional = schema instanceof ZodOptional;
223
- if (isOptional) {
224
- schema = schema.unwrap();
225
- }
226
- const isArray = schema instanceof ZodArray;
227
- if (isArray) {
228
- schema = schema.element;
229
- }
230
- const isObject2 = schema instanceof ZodObject;
231
- return {
232
- ...target,
233
- [key]: {
234
- isArray,
235
- isOptional,
236
- isObject: isObject2
237
- }
238
- };
239
- },
240
- {}
241
- );
242
- }
243
- provideSchema(handlerMetadata) {
244
- const schema = {};
245
- const { querySchema, responseSchema } = handlerMetadata.config;
246
- if (querySchema) {
247
- schema.querystring = querySchema;
248
- }
249
- if (responseSchema) {
250
- schema.response = {
251
- 200: responseSchema
252
- };
253
- }
254
- return schema;
255
- }
256
- };
257
- _init3 = __decoratorStart(_a2);
258
- MultipartAdapterService = __decorateElement(_init3, 0, "MultipartAdapterService", _MultipartAdapterService_decorators, MultipartAdapterService);
259
- __runInitializers(_init3, 1, MultipartAdapterService);
260
39
  function envInt(key, defaultValue) {
261
40
  const envKey = env[key] || process.env[key];
262
41
  return envKey ? parseInt(envKey, 10) : defaultValue;
@@ -303,515 +82,66 @@ function filterLogLevels(parseableString = "") {
303
82
  const logLevelIndex = LOG_LEVELS.indexOf(
304
83
  sanitizedString.substring(orEqual ? 2 : 1)
305
84
  );
306
- if (logLevelIndex === -1) {
307
- throw new Error(`parse error (unknown log level): ${sanitizedString}`);
308
- }
309
- return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
310
- } else if (sanitizedString.includes(",")) {
311
- return sanitizedString.split(",").filter(isLogLevel);
312
- }
313
- return isLogLevel(sanitizedString) ? [sanitizedString] : LOG_LEVELS;
314
- }
315
-
316
- // src/logger/utils/is-log-level-enabled.mts
317
- var LOG_LEVEL_VALUES = {
318
- verbose: 0,
319
- debug: 1,
320
- log: 2,
321
- warn: 3,
322
- error: 4,
323
- fatal: 5
324
- };
325
- function isLogLevelEnabled(targetLevel, logLevels) {
326
- if (!logLevels || Array.isArray(logLevels) && logLevels?.length === 0) {
327
- return false;
328
- }
329
- if (logLevels.includes(targetLevel)) {
330
- return true;
331
- }
332
- const highestLogLevelValue = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)?.[0];
333
- const targetLevelValue = LOG_LEVEL_VALUES[targetLevel];
334
- return targetLevelValue >= highestLogLevelValue;
335
- }
336
-
337
- // src/logger/utils/shared.utils.mts
338
- var isUndefined = (obj) => typeof obj === "undefined";
339
- var isObject = (fn) => !isNil(fn) && typeof fn === "object";
340
- var isPlainObject = (fn) => {
341
- if (!isObject(fn)) {
342
- return false;
343
- }
344
- const proto = Object.getPrototypeOf(fn);
345
- if (proto === null) {
346
- return true;
347
- }
348
- const ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
349
- return typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
350
- };
351
- var addLeadingSlash = (path) => path && typeof path === "string" ? path.charAt(0) !== "/" && path.substring(0, 2) !== "{/" ? "/" + path : path : "";
352
- var normalizePath = (path) => path ? path.startsWith("/") ? ("/" + path.replace(/\/+$/, "")).replace(/\/+/g, "/") : "/" + path.replace(/\/+$/, "") : "/";
353
- var stripEndSlash = (path) => path[path.length - 1] === "/" ? path.slice(0, path.length - 1) : path;
354
- var isFunction = (val) => typeof val === "function";
355
- var isString = (val) => typeof val === "string";
356
- var isNumber = (val) => typeof val === "number";
357
- var isConstructor = (val) => val === "constructor";
358
- var isNil = (val) => isUndefined(val) || val === null;
359
- var isEmpty = (array) => !(array && array.length > 0);
360
- var isSymbol = (val) => typeof val === "symbol";
361
- var ApplicationInjectionToken = "ApplicationInjectionToken";
362
- var Application = InjectionToken.create(
363
- ApplicationInjectionToken
364
- );
365
-
366
- // src/metadata/handler.metadata.mts
367
- var EndpointMetadataKey = Symbol("EndpointMetadataKey");
368
- function getAllEndpointMetadata(context) {
369
- if (context.metadata) {
370
- const metadata = context.metadata[EndpointMetadataKey];
371
- if (metadata) {
372
- return metadata;
373
- } else {
374
- context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
375
- return context.metadata[EndpointMetadataKey];
376
- }
377
- }
378
- throw new Error("[Navios] Wrong environment.");
379
- }
380
- function getEndpointMetadata(target, context) {
381
- if (context.metadata) {
382
- const metadata = getAllEndpointMetadata(context);
383
- if (metadata) {
384
- const endpointMetadata = Array.from(metadata).find(
385
- (item) => item.classMethod === target.name
386
- );
387
- if (endpointMetadata) {
388
- return endpointMetadata;
389
- } else {
390
- const newMetadata = {
391
- classMethod: target.name,
392
- url: "",
393
- successStatusCode: 200,
394
- adapterToken: null,
395
- headers: {},
396
- httpMethod: "GET",
397
- // @ts-expect-error We are using a generic type here
398
- config: null,
399
- guards: /* @__PURE__ */ new Set(),
400
- customAttributes: /* @__PURE__ */ new Map()
401
- };
402
- metadata.add(newMetadata);
403
- return newMetadata;
404
- }
405
- }
406
- }
407
- throw new Error("[Navios] Wrong environment.");
408
- }
409
-
410
- // src/metadata/controller.metadata.mts
411
- var ControllerMetadataKey = Symbol("ControllerMetadataKey");
412
- function getControllerMetadata(target, context) {
413
- if (context.metadata) {
414
- const metadata = context.metadata[ControllerMetadataKey];
415
- if (metadata) {
416
- return metadata;
417
- } else {
418
- const endpointsMetadata = getAllEndpointMetadata(context);
419
- const newMetadata = {
420
- endpoints: endpointsMetadata,
421
- guards: /* @__PURE__ */ new Set(),
422
- customAttributes: /* @__PURE__ */ new Map()
423
- };
424
- context.metadata[ControllerMetadataKey] = newMetadata;
425
- target[ControllerMetadataKey] = newMetadata;
426
- return newMetadata;
427
- }
428
- }
429
- throw new Error("[Navios] Wrong environment.");
430
- }
431
- function extractControllerMetadata(target) {
432
- const metadata = target[ControllerMetadataKey];
433
- if (!metadata) {
434
- throw new Error(
435
- "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
436
- );
437
- }
438
- return metadata;
439
- }
440
- function hasControllerMetadata(target) {
441
- const metadata = target[ControllerMetadataKey];
442
- return !!metadata;
443
- }
444
-
445
- // src/metadata/module.metadata.mts
446
- var ModuleMetadataKey = Symbol("ControllerMetadataKey");
447
- function getModuleMetadata(target, context) {
448
- if (context.metadata) {
449
- const metadata = context.metadata[ModuleMetadataKey];
450
- if (metadata) {
451
- return metadata;
452
- } else {
453
- const newMetadata = {
454
- controllers: /* @__PURE__ */ new Set(),
455
- imports: /* @__PURE__ */ new Set(),
456
- guards: /* @__PURE__ */ new Set(),
457
- customAttributes: /* @__PURE__ */ new Map()
458
- };
459
- context.metadata[ModuleMetadataKey] = newMetadata;
460
- target[ModuleMetadataKey] = newMetadata;
461
- return newMetadata;
462
- }
463
- }
464
- throw new Error("[Navios] Wrong environment.");
465
- }
466
- function extractModuleMetadata(target) {
467
- const metadata = target[ModuleMetadataKey];
468
- if (!metadata) {
469
- throw new Error(
470
- `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
471
- );
472
- }
473
- return metadata;
474
- }
475
- function hasModuleMetadata(target) {
476
- return !!target[ModuleMetadataKey];
477
- }
478
-
479
- // src/services/execution-context.mts
480
- var ExecutionContext = class {
481
- constructor(module, controller, handler) {
482
- this.module = module;
483
- this.controller = controller;
484
- this.handler = handler;
485
- }
486
- request;
487
- reply;
488
- getModule() {
489
- return this.module;
490
- }
491
- getController() {
492
- return this.controller;
493
- }
494
- getHandler() {
495
- return this.handler;
496
- }
497
- getRequest() {
498
- if (!this.request) {
499
- throw new Error(
500
- "[Navios] Request is not set. Make sure to set it before using it."
501
- );
502
- }
503
- return this.request;
504
- }
505
- getReply() {
506
- if (!this.reply) {
507
- throw new Error(
508
- "[Navios] Reply is not set. Make sure to set it before using it."
509
- );
510
- }
511
- return this.reply;
512
- }
513
- provideRequest(request) {
514
- this.request = request;
515
- }
516
- provideReply(reply) {
517
- this.reply = reply;
518
- }
519
- };
520
-
521
- // src/exceptions/http.exception.mts
522
- var HttpException = class {
523
- constructor(statusCode, response, error) {
524
- this.statusCode = statusCode;
525
- this.response = response;
526
- this.error = error;
527
- }
528
- };
529
-
530
- // src/exceptions/bad-request.exception.mts
531
- var BadRequestException = class extends HttpException {
532
- constructor(message) {
533
- super(400, message);
534
- }
535
- };
536
-
537
- // src/exceptions/forbidden.exception.mts
538
- var ForbiddenException = class extends HttpException {
539
- constructor(message) {
540
- super(403, message);
541
- }
542
- };
543
-
544
- // src/exceptions/internal-server-error.exception.mts
545
- var InternalServerErrorException = class extends HttpException {
546
- constructor(message, error) {
547
- super(500, message, error);
548
- }
549
- };
550
-
551
- // src/exceptions/not-found.exception.mts
552
- var NotFoundException = class extends HttpException {
553
- constructor(response, error) {
554
- super(404, response, error);
555
- this.response = response;
556
- this.error = error;
557
- }
558
- };
559
-
560
- // src/exceptions/unauthorized.exception.mts
561
- var UnauthorizedException = class extends HttpException {
562
- constructor(message, error) {
563
- super(401, message, error);
564
- }
565
- };
566
-
567
- // src/exceptions/conflict.exception.mts
568
- var ConflictException = class extends HttpException {
569
- constructor(message, error) {
570
- super(409, message, error);
571
- }
572
- };
573
-
574
- // src/services/guard-runner.service.mts
575
- var _GuardRunnerService_decorators, _init4;
576
- _GuardRunnerService_decorators = [Injectable()];
577
- var GuardRunnerService = class {
578
- async runGuards(allGuards, executionContext) {
579
- let canActivate = true;
580
- for (const guard of Array.from(allGuards).reverse()) {
581
- const guardInstance = await inject(
582
- guard
583
- );
584
- if (!guardInstance.canActivate) {
585
- throw new Error(
586
- `[Navios] Guard ${guard.name} does not implement canActivate()`
587
- );
588
- }
589
- try {
590
- canActivate = await guardInstance.canActivate(executionContext);
591
- if (!canActivate) {
592
- break;
593
- }
594
- } catch (error) {
595
- if (error instanceof HttpException) {
596
- executionContext.getReply().status(error.statusCode).send(error.response);
597
- return false;
598
- } else {
599
- executionContext.getReply().status(500).send({
600
- message: "Internal server error",
601
- error: error.message
602
- });
603
- return false;
604
- }
605
- }
606
- }
607
- if (!canActivate) {
608
- executionContext.getReply().status(403).send({
609
- message: "Forbidden"
610
- });
611
- return false;
612
- }
613
- return canActivate;
614
- }
615
- makeContext(executionContext) {
616
- const guards = /* @__PURE__ */ new Set();
617
- const endpointGuards = executionContext.getHandler().guards;
618
- const controllerGuards = executionContext.getController().guards;
619
- const moduleGuards = executionContext.getModule().guards;
620
- if (endpointGuards.size > 0) {
621
- for (const guard of endpointGuards) {
622
- guards.add(guard);
623
- }
624
- }
625
- if (controllerGuards.size > 0) {
626
- for (const guard of controllerGuards) {
627
- guards.add(guard);
628
- }
629
- }
630
- if (moduleGuards.size > 0) {
631
- for (const guard of moduleGuards) {
632
- guards.add(guard);
633
- }
634
- }
635
- return guards;
636
- }
637
- };
638
- _init4 = __decoratorStart(null);
639
- GuardRunnerService = __decorateElement(_init4, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
640
- __runInitializers(_init4, 1, GuardRunnerService);
641
-
642
- // src/services/controller-adapter.service.mts
643
- var _ControllerAdapterService_decorators, _init5;
644
- _ControllerAdapterService_decorators = [Injectable()];
645
- var _ControllerAdapterService = class _ControllerAdapterService {
646
- guardRunner = syncInject(GuardRunnerService);
647
- logger = syncInject(Logger, {
648
- context: _ControllerAdapterService.name
649
- });
650
- async setupController(controller, instance, moduleMetadata) {
651
- const controllerMetadata = extractControllerMetadata(controller);
652
- for (const endpoint of controllerMetadata.endpoints) {
653
- const { classMethod, url, httpMethod, adapterToken } = endpoint;
654
- if (!url || !adapterToken) {
655
- throw new Error(
656
- `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
657
- );
658
- }
659
- const adapter = await inject(
660
- adapterToken
661
- );
662
- const executionContext = new ExecutionContext(
663
- moduleMetadata,
664
- controllerMetadata,
665
- endpoint
666
- );
667
- const hasSchema = adapter.hasSchema?.(endpoint) ?? false;
668
- if (hasSchema) {
669
- instance.withTypeProvider().route({
670
- method: httpMethod,
671
- url: url.replaceAll("$", ":"),
672
- schema: adapter.provideSchema?.(endpoint) ?? {},
673
- preHandler: this.providePreHandler(executionContext),
674
- handler: this.wrapHandler(
675
- executionContext,
676
- adapter.provideHandler(controller, executionContext, endpoint)
677
- )
678
- });
679
- } else {
680
- instance.route({
681
- method: httpMethod,
682
- url: url.replaceAll("$", ":"),
683
- preHandler: this.providePreHandler(executionContext),
684
- handler: this.wrapHandler(
685
- executionContext,
686
- adapter.provideHandler(controller, executionContext, endpoint)
687
- )
688
- });
689
- }
690
- this.logger.debug(
691
- `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
692
- );
693
- }
694
- }
695
- providePreHandler(executionContext) {
696
- const guards = this.guardRunner.makeContext(executionContext);
697
- return guards.size > 0 ? this.wrapHandler(
698
- executionContext,
699
- async (request, reply) => {
700
- let canActivate = true;
701
- canActivate = await this.guardRunner.runGuards(
702
- guards,
703
- executionContext
704
- );
705
- if (!canActivate) {
706
- return reply;
707
- }
708
- }
709
- ) : void 0;
710
- }
711
- wrapHandler(executionContext, handler) {
712
- const locator = getGlobalServiceLocator();
713
- return async (request, reply) => {
714
- locator.storeInstance(request, Request);
715
- locator.storeInstance(reply, Reply);
716
- locator.storeInstance(executionContext, ExecutionContextToken);
717
- executionContext.provideRequest(request);
718
- executionContext.provideReply(reply);
719
- try {
720
- return await handler(request, reply);
721
- } finally {
722
- Promise.all([
723
- locator.removeInstance(Request),
724
- locator.removeInstance(Reply),
725
- locator.removeInstance(ExecutionContextToken)
726
- ]).catch((err) => {
727
- this.logger.warn(`Error removing instances: ${err}`);
728
- });
729
- }
730
- };
731
- }
732
- };
733
- _init5 = __decoratorStart(null);
734
- _ControllerAdapterService = __decorateElement(_init5, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
735
- __runInitializers(_init5, 1, _ControllerAdapterService);
736
- var ControllerAdapterService = _ControllerAdapterService;
737
- var _ModuleLoaderService_decorators, _init6;
738
- _ModuleLoaderService_decorators = [Injectable()];
739
- var _ModuleLoaderService = class _ModuleLoaderService {
740
- logger = syncInject(Logger, {
741
- context: _ModuleLoaderService.name
742
- });
743
- modulesMetadata = /* @__PURE__ */ new Map();
744
- loadedModules = /* @__PURE__ */ new Map();
745
- initialized = false;
746
- async loadModules(appModule) {
747
- if (this.initialized) {
748
- return;
749
- }
750
- await this.traverseModules(appModule);
751
- this.initialized = true;
752
- }
753
- async traverseModules(module, parentMetadata) {
754
- const metadata = extractModuleMetadata(module);
755
- if (parentMetadata) {
756
- this.mergeMetadata(metadata, parentMetadata);
757
- }
758
- const moduleName = module.name;
759
- if (this.modulesMetadata.has(moduleName)) {
760
- return;
761
- }
762
- this.modulesMetadata.set(moduleName, metadata);
763
- const imports = metadata.imports ?? /* @__PURE__ */ new Set();
764
- const loadingPromises = Array.from(imports).map(
765
- async (importedModule) => this.traverseModules(importedModule, metadata)
766
- );
767
- await Promise.all(loadingPromises);
768
- const instance = await inject(module);
769
- if (instance.onModuleInit) {
770
- await instance.onModuleInit();
85
+ if (logLevelIndex === -1) {
86
+ throw new Error(`parse error (unknown log level): ${sanitizedString}`);
771
87
  }
772
- this.logger.debug(`Module ${moduleName} loaded`);
773
- this.loadedModules.set(moduleName, instance);
88
+ return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
89
+ } else if (sanitizedString.includes(",")) {
90
+ return sanitizedString.split(",").filter(isLogLevel);
774
91
  }
775
- mergeMetadata(metadata, parentMetadata) {
776
- if (parentMetadata.guards) {
777
- for (const guard of parentMetadata.guards) {
778
- metadata.guards.add(guard);
779
- }
780
- }
781
- if (parentMetadata.customAttributes) {
782
- for (const [key, value] of parentMetadata.customAttributes) {
783
- if (metadata.customAttributes.has(key)) {
784
- continue;
785
- }
786
- metadata.customAttributes.set(key, value);
787
- }
788
- }
92
+ return isLogLevel(sanitizedString) ? [sanitizedString] : LOG_LEVELS;
93
+ }
94
+
95
+ // src/logger/utils/is-log-level-enabled.mts
96
+ var LOG_LEVEL_VALUES = {
97
+ verbose: 0,
98
+ debug: 1,
99
+ log: 2,
100
+ warn: 3,
101
+ error: 4,
102
+ fatal: 5
103
+ };
104
+ function isLogLevelEnabled(targetLevel, logLevels) {
105
+ if (!logLevels || Array.isArray(logLevels) && logLevels?.length === 0) {
106
+ return false;
789
107
  }
790
- getAllModules() {
791
- return this.modulesMetadata;
108
+ if (logLevels.includes(targetLevel)) {
109
+ return true;
792
110
  }
793
- dispose() {
794
- this.modulesMetadata.clear();
795
- this.loadedModules.clear();
796
- this.initialized = false;
111
+ const highestLogLevelValue = logLevels.map((level) => LOG_LEVEL_VALUES[level]).sort((a, b) => b - a)?.[0];
112
+ const targetLevelValue = LOG_LEVEL_VALUES[targetLevel];
113
+ return targetLevelValue >= highestLogLevelValue;
114
+ }
115
+
116
+ // src/logger/utils/shared.utils.mts
117
+ var isUndefined = (obj) => typeof obj === "undefined";
118
+ var isObject = (fn) => !isNil(fn) && typeof fn === "object";
119
+ var isPlainObject = (fn) => {
120
+ if (!isObject(fn)) {
121
+ return false;
122
+ }
123
+ const proto = Object.getPrototypeOf(fn);
124
+ if (proto === null) {
125
+ return true;
797
126
  }
127
+ const ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
128
+ return typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
798
129
  };
799
- _init6 = __decoratorStart(null);
800
- _ModuleLoaderService = __decorateElement(_init6, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
801
- __runInitializers(_init6, 1, _ModuleLoaderService);
802
- var ModuleLoaderService = _ModuleLoaderService;
803
-
804
- // src/tokens/execution-context.token.mts
805
- var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
806
- var ExecutionContextToken = InjectionToken.create(
807
- ExecutionContextInjectionToken
808
- );
809
- var ReplyInjectionToken = "ReplyInjectionToken";
810
- var Reply = InjectionToken.create(ReplyInjectionToken);
811
- var RequestInjectionToken = "RequestInjectionToken";
812
- var Request = InjectionToken.create(
813
- RequestInjectionToken
814
- );
130
+ var addLeadingSlash = (path) => path && typeof path === "string" ? path.charAt(0) !== "/" && path.substring(0, 2) !== "{/" ? "/" + path : path : "";
131
+ var normalizePath = (path) => path ? path.startsWith("/") ? ("/" + path.replace(/\/+$/, "")).replace(/\/+/g, "/") : "/" + path.replace(/\/+$/, "") : "/";
132
+ var stripEndSlash = (path) => path[path.length - 1] === "/" ? path.slice(0, path.length - 1) : path;
133
+ var isFunction = (val) => typeof val === "function";
134
+ var isString = (val) => typeof val === "string";
135
+ var isNumber = (val) => typeof val === "number";
136
+ var isConstructor = (val) => val === "constructor";
137
+ var isNil = (val) => isUndefined(val) || val === null;
138
+ var isEmpty = (array) => !(array && array.length > 0);
139
+ var isSymbol = (val) => typeof val === "symbol";
140
+ var LoggerOutput = InjectionToken.create("LoggerOutput");
141
+ var loggerOptionsSchema = z.object({
142
+ context: z.string().optional()
143
+ }).optional();
144
+ var Logger = InjectionToken.create("Logger", loggerOptionsSchema);
815
145
 
816
146
  // src/logger/console-logger.service.mts
817
147
  var DEFAULT_DEPTH = 5;
@@ -831,21 +161,19 @@ var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
831
161
  day: "2-digit",
832
162
  month: "2-digit"
833
163
  });
834
- var _ConsoleLogger_decorators, _init7;
835
- _ConsoleLogger_decorators = [Injectable()];
836
- var _ConsoleLogger = class _ConsoleLogger {
164
+ var _ConsoleLogger_decorators, _init;
165
+ _ConsoleLogger_decorators = [Injectable({
166
+ token: LoggerOutput
167
+ })];
168
+ var ConsoleLogger = class {
837
169
  /**
838
170
  * The options of the logger.
839
171
  */
840
- options;
172
+ options = {};
841
173
  /**
842
174
  * The context of the logger (can be set manually or automatically inferred).
843
175
  */
844
176
  context;
845
- /**
846
- * Request ID (if enabled).
847
- */
848
- requestId = null;
849
177
  /**
850
178
  * The original context of the logger (set in the constructor).
851
179
  */
@@ -853,12 +181,12 @@ var _ConsoleLogger = class _ConsoleLogger {
853
181
  /**
854
182
  * The options used for the "inspect" method.
855
183
  */
856
- inspectOptions;
184
+ inspectOptions = this.getInspectOptions();
857
185
  /**
858
186
  * The last timestamp at which the log message was printed.
859
187
  */
860
- static lastTimestampAt;
861
- constructor(contextOrOptions, options) {
188
+ lastTimestampAt;
189
+ setup(contextOrOptions, options) {
862
190
  let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions?.context, contextOrOptions];
863
191
  opts = opts ?? {};
864
192
  opts.logLevels ??= DEFAULT_LOG_LEVELS;
@@ -870,20 +198,6 @@ var _ConsoleLogger = class _ConsoleLogger {
870
198
  this.context = context;
871
199
  this.originalContext = context;
872
200
  }
873
- if (opts?.requestId) {
874
- const locator = getGlobalServiceLocator();
875
- locator.getEventBus().on(locator.getInstanceIdentifier(Request, void 0), "create", () => {
876
- const request = locator.getSyncInstance(Request, void 0);
877
- this.requestId = request?.id ?? null;
878
- });
879
- locator.getEventBus().on(
880
- locator.getInstanceIdentifier(Request, void 0),
881
- "destroy",
882
- () => {
883
- this.requestId = null;
884
- }
885
- );
886
- }
887
201
  }
888
202
  log(message, ...optionalParams) {
889
203
  if (!this.isLevelEnabled("log")) {
@@ -900,7 +214,7 @@ var _ConsoleLogger = class _ConsoleLogger {
900
214
  return;
901
215
  }
902
216
  const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
903
- this.printMessages(messages, context, "error", "stderr", stack);
217
+ this.printMessages(messages, context, "error", void 0, "stderr", stack);
904
218
  this.printStackTrace(stack);
905
219
  }
906
220
  warn(message, ...optionalParams) {
@@ -973,14 +287,15 @@ var _ConsoleLogger = class _ConsoleLogger {
973
287
  getTimestamp() {
974
288
  return dateTimeFormatter.format(Date.now());
975
289
  }
976
- printMessages(messages, context = "", logLevel = "log", writeStreamType, errorStack) {
290
+ printMessages(messages, context = "", logLevel = "log", requestId, writeStreamType, errorStack) {
977
291
  messages.forEach((message) => {
978
292
  if (this.options.json) {
979
293
  this.printAsJson(message, {
980
294
  context,
981
295
  logLevel,
982
296
  writeStreamType,
983
- errorStack
297
+ errorStack,
298
+ requestId
984
299
  });
985
300
  return;
986
301
  }
@@ -994,7 +309,8 @@ var _ConsoleLogger = class _ConsoleLogger {
994
309
  pidMessage,
995
310
  formattedLogLevel,
996
311
  contextMessage,
997
- timestampDiff
312
+ timestampDiff,
313
+ requestId
998
314
  );
999
315
  process[writeStreamType ?? "stdout"].write(formattedMessage);
1000
316
  });
@@ -1012,8 +328,8 @@ var _ConsoleLogger = class _ConsoleLogger {
1012
328
  if (options.errorStack) {
1013
329
  logObject.stack = options.errorStack;
1014
330
  }
1015
- if (this.options.requestId && this.requestId) {
1016
- logObject.requestId = this.requestId;
331
+ if (this.options.requestId && options.requestId) {
332
+ logObject.requestId = options.requestId;
1017
333
  }
1018
334
  const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : inspect(logObject, this.inspectOptions);
1019
335
  process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
@@ -1029,16 +345,16 @@ var _ConsoleLogger = class _ConsoleLogger {
1029
345
  context = `[${context}] `;
1030
346
  return this.options.colors ? yellow(context) : context;
1031
347
  }
1032
- formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
348
+ formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff, requestId) {
1033
349
  const output = this.stringifyMessage(message, logLevel);
1034
350
  pidMessage = this.colorize(pidMessage, logLevel);
1035
351
  formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
1036
- return `${pidMessage}${this.getRequestId()}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
352
+ return `${pidMessage}${this.getRequestId(requestId)}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
1037
353
  `;
1038
354
  }
1039
- getRequestId() {
1040
- if (this.options.requestId && this.requestId) {
1041
- return `(${this.colorize(this.requestId, "log")}) `;
355
+ getRequestId(requestId) {
356
+ if (this.options.requestId && requestId) {
357
+ return `(${this.colorize(requestId, "log")}) `;
1042
358
  }
1043
359
  return "";
1044
360
  }
@@ -1078,9 +394,9 @@ var _ConsoleLogger = class _ConsoleLogger {
1078
394
  `);
1079
395
  }
1080
396
  updateAndGetTimestampDiff() {
1081
- const includeTimestamp = _ConsoleLogger.lastTimestampAt && this.options?.timestamp;
1082
- const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
1083
- _ConsoleLogger.lastTimestampAt = Date.now();
397
+ const includeTimestamp = this.lastTimestampAt && this.options?.timestamp;
398
+ const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt) : "";
399
+ this.lastTimestampAt = Date.now();
1084
400
  return result;
1085
401
  }
1086
402
  formatTimestampDiff(timestampDiff) {
@@ -1183,39 +499,18 @@ var _ConsoleLogger = class _ConsoleLogger {
1183
499
  }
1184
500
  }
1185
501
  };
1186
- _init7 = __decoratorStart(null);
1187
- _ConsoleLogger = __decorateElement(_init7, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
1188
- __runInitializers(_init7, 1, _ConsoleLogger);
1189
- var ConsoleLogger = _ConsoleLogger;
1190
- var DEFAULT_LOGGER = new ConsoleLogger();
1191
- var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
1192
- year: "numeric",
1193
- hour: "numeric",
1194
- minute: "numeric",
1195
- second: "numeric",
1196
- day: "2-digit",
1197
- month: "2-digit"
1198
- });
1199
- var _LoggerInstance_decorators, _init8;
1200
- _LoggerInstance_decorators = [Injectable()];
1201
- var _LoggerInstance = class _LoggerInstance {
1202
- constructor(context, options = {}) {
1203
- this.context = context;
1204
- this.options = options;
1205
- }
1206
- static staticInstanceRef = DEFAULT_LOGGER;
1207
- static logLevels;
1208
- localInstanceRef;
1209
- get localInstance() {
1210
- if (_LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {
1211
- return this.registerLocalInstanceRef();
1212
- } else if (_LoggerInstance.staticInstanceRef instanceof _LoggerInstance) {
1213
- const prototype = Object.getPrototypeOf(_LoggerInstance.staticInstanceRef);
1214
- if (prototype.constructor === _LoggerInstance) {
1215
- return this.registerLocalInstanceRef();
1216
- }
1217
- }
1218
- return _LoggerInstance.staticInstanceRef;
502
+ _init = __decoratorStart();
503
+ ConsoleLogger = __decorateElement(_init, 0, "ConsoleLogger", _ConsoleLogger_decorators, ConsoleLogger);
504
+ __runInitializers(_init, 1, ConsoleLogger);
505
+ var _LoggerInstance_decorators, _init2;
506
+ _LoggerInstance_decorators = [Injectable({
507
+ token: Logger
508
+ })];
509
+ var LoggerInstance = class {
510
+ localInstance = inject(LoggerOutput);
511
+ context;
512
+ constructor(config = {}) {
513
+ this.context = config.context;
1219
514
  }
1220
515
  error(message, ...optionalParams) {
1221
516
  optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
@@ -1243,135 +538,15 @@ var _LoggerInstance = class _LoggerInstance {
1243
538
  optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1244
539
  this.localInstance?.fatal?.(message, ...optionalParams);
1245
540
  }
1246
- static error(message, ...optionalParams) {
1247
- this.staticInstanceRef?.error(message, ...optionalParams);
1248
- }
1249
- static log(message, ...optionalParams) {
1250
- this.staticInstanceRef?.log(message, ...optionalParams);
1251
- }
1252
- static warn(message, ...optionalParams) {
1253
- this.staticInstanceRef?.warn(message, ...optionalParams);
1254
- }
1255
- static debug(message, ...optionalParams) {
1256
- this.staticInstanceRef?.debug?.(message, ...optionalParams);
1257
- }
1258
- static verbose(message, ...optionalParams) {
1259
- this.staticInstanceRef?.verbose?.(message, ...optionalParams);
1260
- }
1261
- static fatal(message, ...optionalParams) {
1262
- this.staticInstanceRef?.fatal?.(message, ...optionalParams);
1263
- }
1264
- static getTimestamp() {
1265
- return dateTimeFormatter2.format(Date.now());
1266
- }
1267
- static overrideLogger(logger) {
1268
- if (Array.isArray(logger)) {
1269
- _LoggerInstance.logLevels = logger;
1270
- return this.staticInstanceRef?.setLogLevels?.(logger);
1271
- }
1272
- if (isObject(logger)) {
1273
- this.staticInstanceRef = logger;
1274
- } else {
1275
- this.staticInstanceRef = void 0;
1276
- }
1277
- }
1278
- static isLevelEnabled(level) {
1279
- const logLevels = _LoggerInstance.logLevels;
1280
- return isLogLevelEnabled(level, logLevels);
1281
- }
1282
- registerLocalInstanceRef() {
1283
- if (this.localInstanceRef) {
1284
- return this.localInstanceRef;
1285
- }
1286
- this.localInstanceRef = new ConsoleLogger(this.context, {
1287
- timestamp: this.options?.timestamp,
1288
- logLevels: _LoggerInstance.logLevels
1289
- });
1290
- return this.localInstanceRef;
1291
- }
1292
- };
1293
- _init8 = __decoratorStart(null);
1294
- _LoggerInstance = __decorateElement(_init8, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
1295
- __runInitializers(_init8, 1, _LoggerInstance);
1296
- var LoggerInstance = _LoggerInstance;
1297
-
1298
- // src/logger/logger.factory.mts
1299
- var LoggerInjectionToken = "LoggerInjectionToken";
1300
- var LoggerOptions = z.object({
1301
- context: z.string().optional(),
1302
- options: z.object({
1303
- timestamp: z.boolean().optional()
1304
- }).optional()
1305
- }).optional();
1306
- var Logger = InjectionToken.create(LoggerInjectionToken, LoggerOptions);
1307
- var _LoggerFactory_decorators, _init9;
1308
- _LoggerFactory_decorators = [Injectable({
1309
- type: InjectableType.Factory,
1310
- token: Logger
1311
- })];
1312
- var LoggerFactory = class {
1313
- create(ctx, args) {
1314
- return new LoggerInstance(args?.context, args?.options);
1315
- }
1316
- };
1317
- _init9 = __decoratorStart(null);
1318
- LoggerFactory = __decorateElement(_init9, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
1319
- __runInitializers(_init9, 1, LoggerFactory);
1320
-
1321
- // src/logger/pino-wrapper.mts
1322
- var PinoWrapper = class _PinoWrapper {
1323
- constructor(logger) {
1324
- this.logger = logger;
1325
- }
1326
- fatal(message, ...optionalParams) {
1327
- if (this.logger.fatal === void 0) {
1328
- return this.error(message, ...optionalParams);
1329
- }
1330
- this.logger.fatal(message, ...optionalParams);
1331
- }
1332
- error(message, ...optionalParams) {
1333
- this.logger.error(message, ...optionalParams);
1334
- }
1335
- warn(message, ...optionalParams) {
1336
- this.logger.warn(message, ...optionalParams);
1337
- }
1338
- info() {
1339
- }
1340
- debug(message, ...optionalParams) {
1341
- this.logger.debug?.(message, ...optionalParams);
1342
- }
1343
- trace(message, ...optionalParams) {
1344
- this.logger.verbose?.(message, ...optionalParams);
1345
- }
1346
- silent() {
1347
- }
1348
- child(options) {
1349
- const keys = Object.keys(options);
1350
- let newContext = this.logger["context"] ?? "";
1351
- if (keys.length > 1) {
1352
- newContext = `${this.logger["context"] ?? ""}:${JSON.stringify(options)}`;
1353
- }
1354
- return new _PinoWrapper(
1355
- // @ts-expect-error We don't need to support this in the current version
1356
- new LoggerInstance(newContext, this.logger["options"])
1357
- );
1358
- }
1359
- get level() {
1360
- if ("level" in this.logger && this.logger.level) {
1361
- return this.logger.level;
1362
- }
1363
- const levels = LoggerInstance["logLevels"];
1364
- if (levels) {
1365
- return levels.find((level) => level !== "verbose");
1366
- }
1367
- return "warn";
1368
- }
1369
541
  };
542
+ _init2 = __decoratorStart();
543
+ LoggerInstance = __decorateElement(_init2, 0, "LoggerInstance", _LoggerInstance_decorators, LoggerInstance);
544
+ __runInitializers(_init2, 1, LoggerInstance);
1370
545
 
1371
546
  // src/config/config.service.mts
1372
- var ConfigServiceOptionsSchema = z.record(z.string(), z.unknown());
547
+ var ConfigServiceOptionsSchema = z$1.record(z$1.string(), z$1.unknown());
1373
548
  var ConfigServiceToken = InjectionToken.create(Symbol.for("ConfigService"), ConfigServiceOptionsSchema);
1374
- var _ConfigService_decorators, _init10;
549
+ var _ConfigService_decorators, _init3;
1375
550
  _ConfigService_decorators = [Injectable({
1376
551
  token: ConfigServiceToken
1377
552
  })];
@@ -1379,7 +554,7 @@ var _ConfigService = class _ConfigService {
1379
554
  constructor(config = {}) {
1380
555
  this.config = config;
1381
556
  }
1382
- logger = syncInject(Logger, {
557
+ logger = inject(Logger, {
1383
558
  context: _ConfigService.name
1384
559
  });
1385
560
  getConfig() {
@@ -1418,14 +593,14 @@ var _ConfigService = class _ConfigService {
1418
593
  return value;
1419
594
  }
1420
595
  };
1421
- _init10 = __decoratorStart(null);
1422
- _ConfigService = __decorateElement(_init10, 0, "ConfigService", _ConfigService_decorators, _ConfigService);
1423
- __runInitializers(_init10, 1, _ConfigService);
596
+ _init3 = __decoratorStart();
597
+ _ConfigService = __decorateElement(_init3, 0, "ConfigService", _ConfigService_decorators, _ConfigService);
598
+ __runInitializers(_init3, 1, _ConfigService);
1424
599
  var ConfigService = _ConfigService;
1425
600
 
1426
601
  // src/config/config.provider.mts
1427
- var ConfigProviderOptions = z.object({
1428
- load: z.function({ output: ConfigServiceOptionsSchema })
602
+ var ConfigProviderOptions = z$1.object({
603
+ load: z$1.function({ output: ConfigServiceOptionsSchema })
1429
604
  });
1430
605
  function provideConfig(options) {
1431
606
  return InjectionToken.factory(ConfigServiceToken, async () => options.load());
@@ -1433,6 +608,121 @@ function provideConfig(options) {
1433
608
  var EnvConfigProvider = InjectionToken.bound(ConfigServiceToken, {
1434
609
  ...env
1435
610
  });
611
+
612
+ // src/metadata/handler.metadata.mts
613
+ var EndpointMetadataKey = Symbol("EndpointMetadataKey");
614
+ function getAllEndpointMetadata(context) {
615
+ if (context.metadata) {
616
+ const metadata = context.metadata[EndpointMetadataKey];
617
+ if (metadata) {
618
+ return metadata;
619
+ } else {
620
+ context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
621
+ return context.metadata[EndpointMetadataKey];
622
+ }
623
+ }
624
+ throw new Error("[Navios] Wrong environment.");
625
+ }
626
+ function getEndpointMetadata(target, context) {
627
+ if (context.metadata) {
628
+ const metadata = getAllEndpointMetadata(context);
629
+ if (metadata) {
630
+ const endpointMetadata = Array.from(metadata).find(
631
+ (item) => item.classMethod === target.name
632
+ );
633
+ if (endpointMetadata) {
634
+ return endpointMetadata;
635
+ } else {
636
+ const newMetadata = {
637
+ classMethod: target.name,
638
+ url: "",
639
+ successStatusCode: 200,
640
+ adapterToken: null,
641
+ headers: {},
642
+ httpMethod: "GET",
643
+ // @ts-expect-error We are using a generic type here
644
+ config: null,
645
+ guards: /* @__PURE__ */ new Set(),
646
+ customAttributes: /* @__PURE__ */ new Map()
647
+ };
648
+ metadata.add(newMetadata);
649
+ return newMetadata;
650
+ }
651
+ }
652
+ }
653
+ throw new Error("[Navios] Wrong environment.");
654
+ }
655
+
656
+ // src/metadata/controller.metadata.mts
657
+ var ControllerMetadataKey = Symbol("ControllerMetadataKey");
658
+ function getControllerMetadata(target, context) {
659
+ if (context.metadata) {
660
+ const metadata = context.metadata[ControllerMetadataKey];
661
+ if (metadata) {
662
+ return metadata;
663
+ } else {
664
+ const endpointsMetadata = getAllEndpointMetadata(context);
665
+ const newMetadata = {
666
+ endpoints: endpointsMetadata,
667
+ guards: /* @__PURE__ */ new Set(),
668
+ customAttributes: /* @__PURE__ */ new Map()
669
+ };
670
+ context.metadata[ControllerMetadataKey] = newMetadata;
671
+ target[ControllerMetadataKey] = newMetadata;
672
+ return newMetadata;
673
+ }
674
+ }
675
+ throw new Error("[Navios] Wrong environment.");
676
+ }
677
+ function extractControllerMetadata(target) {
678
+ const metadata = target[ControllerMetadataKey];
679
+ if (!metadata) {
680
+ throw new Error(
681
+ "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
682
+ );
683
+ }
684
+ return metadata;
685
+ }
686
+ function hasControllerMetadata(target) {
687
+ const metadata = target[ControllerMetadataKey];
688
+ return !!metadata;
689
+ }
690
+
691
+ // src/metadata/module.metadata.mts
692
+ var ModuleMetadataKey = Symbol("ControllerMetadataKey");
693
+ function getModuleMetadata(target, context) {
694
+ if (context.metadata) {
695
+ const metadata = context.metadata[ModuleMetadataKey];
696
+ if (metadata) {
697
+ return metadata;
698
+ } else {
699
+ const newMetadata = {
700
+ controllers: /* @__PURE__ */ new Set(),
701
+ imports: /* @__PURE__ */ new Set(),
702
+ guards: /* @__PURE__ */ new Set(),
703
+ customAttributes: /* @__PURE__ */ new Map()
704
+ };
705
+ context.metadata[ModuleMetadataKey] = newMetadata;
706
+ target[ModuleMetadataKey] = newMetadata;
707
+ return newMetadata;
708
+ }
709
+ }
710
+ throw new Error("[Navios] Wrong environment.");
711
+ }
712
+ function extractModuleMetadata(target) {
713
+ const metadata = target[ModuleMetadataKey];
714
+ if (!metadata) {
715
+ throw new Error(
716
+ `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
717
+ );
718
+ }
719
+ return metadata;
720
+ }
721
+ function hasModuleMetadata(target) {
722
+ return !!target[ModuleMetadataKey];
723
+ }
724
+
725
+ // src/decorators/controller.decorator.mts
1436
726
  function Controller({ guards } = {}) {
1437
727
  return function(target, context) {
1438
728
  if (context.kind !== "class") {
@@ -1451,10 +741,30 @@ function Controller({ guards } = {}) {
1451
741
  }
1452
742
  return Injectable({
1453
743
  token,
1454
- scope: InjectableScope.Instance
744
+ scope: InjectableScope.Request
1455
745
  })(target, context);
1456
746
  };
1457
747
  }
748
+ var EndpointAdapterToken = InjectionToken.create(
749
+ "EndpointAdapterToken"
750
+ );
751
+ var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
752
+ var ExecutionContext = InjectionToken.create(
753
+ ExecutionContextInjectionToken
754
+ );
755
+ var HttpAdapterToken = InjectionToken.create(
756
+ "HttpAdapterToken"
757
+ );
758
+ var MultipartAdapterToken = InjectionToken.create(
759
+ "MultipartAdapterToken"
760
+ );
761
+ var Reply = InjectionToken.create("ReplyToken");
762
+ var Request = InjectionToken.create("RequestToken");
763
+ var StreamAdapterToken = InjectionToken.create(
764
+ "StreamAdapterToken"
765
+ );
766
+
767
+ // src/decorators/endpoint.decorator.mts
1458
768
  function Endpoint(endpoint) {
1459
769
  return (target, context) => {
1460
770
  if (context.kind !== "method") {
@@ -1626,6 +936,193 @@ function UseGuards(...guards) {
1626
936
  };
1627
937
  }
1628
938
 
939
+ // src/exceptions/http.exception.mts
940
+ var HttpException = class {
941
+ constructor(statusCode, response, error) {
942
+ this.statusCode = statusCode;
943
+ this.response = response;
944
+ this.error = error;
945
+ }
946
+ };
947
+
948
+ // src/exceptions/bad-request.exception.mts
949
+ var BadRequestException = class extends HttpException {
950
+ constructor(message) {
951
+ super(400, message);
952
+ }
953
+ };
954
+
955
+ // src/exceptions/forbidden.exception.mts
956
+ var ForbiddenException = class extends HttpException {
957
+ constructor(message) {
958
+ super(403, message);
959
+ }
960
+ };
961
+
962
+ // src/exceptions/internal-server-error.exception.mts
963
+ var InternalServerErrorException = class extends HttpException {
964
+ constructor(message, error) {
965
+ super(500, message, error);
966
+ }
967
+ };
968
+
969
+ // src/exceptions/not-found.exception.mts
970
+ var NotFoundException = class extends HttpException {
971
+ constructor(response, error) {
972
+ super(404, response, error);
973
+ this.response = response;
974
+ this.error = error;
975
+ }
976
+ };
977
+
978
+ // src/exceptions/unauthorized.exception.mts
979
+ var UnauthorizedException = class extends HttpException {
980
+ constructor(message, error) {
981
+ super(401, message, error);
982
+ }
983
+ };
984
+
985
+ // src/exceptions/conflict.exception.mts
986
+ var ConflictException = class extends HttpException {
987
+ constructor(message, error) {
988
+ super(409, message, error);
989
+ }
990
+ };
991
+ var _GuardRunnerService_decorators, _init4;
992
+ _GuardRunnerService_decorators = [Injectable()];
993
+ var GuardRunnerService = class {
994
+ container = inject(Container);
995
+ async runGuards(allGuards, executionContext) {
996
+ let canActivate = true;
997
+ for (const guard of Array.from(allGuards).reverse()) {
998
+ const guardInstance = await this.container.get(
999
+ guard
1000
+ );
1001
+ if (!guardInstance.canActivate) {
1002
+ throw new Error(
1003
+ `[Navios] Guard ${guard.name} does not implement canActivate()`
1004
+ );
1005
+ }
1006
+ try {
1007
+ canActivate = await guardInstance.canActivate(executionContext);
1008
+ if (!canActivate) {
1009
+ break;
1010
+ }
1011
+ } catch (error) {
1012
+ if (error instanceof HttpException) {
1013
+ executionContext.getReply().status(error.statusCode).send(error.response);
1014
+ return false;
1015
+ } else {
1016
+ executionContext.getReply().status(500).send({
1017
+ message: "Internal server error",
1018
+ error: error.message
1019
+ });
1020
+ return false;
1021
+ }
1022
+ }
1023
+ }
1024
+ if (!canActivate) {
1025
+ executionContext.getReply().status(403).send({
1026
+ message: "Forbidden"
1027
+ });
1028
+ return false;
1029
+ }
1030
+ return canActivate;
1031
+ }
1032
+ makeContext(moduleMetadata, controllerMetadata, endpoint) {
1033
+ const guards = /* @__PURE__ */ new Set();
1034
+ const endpointGuards = endpoint.guards;
1035
+ const controllerGuards = controllerMetadata.guards;
1036
+ const moduleGuards = moduleMetadata.guards;
1037
+ if (endpointGuards.size > 0) {
1038
+ for (const guard of endpointGuards) {
1039
+ guards.add(guard);
1040
+ }
1041
+ }
1042
+ if (controllerGuards.size > 0) {
1043
+ for (const guard of controllerGuards) {
1044
+ guards.add(guard);
1045
+ }
1046
+ }
1047
+ if (moduleGuards.size > 0) {
1048
+ for (const guard of moduleGuards) {
1049
+ guards.add(guard);
1050
+ }
1051
+ }
1052
+ return guards;
1053
+ }
1054
+ };
1055
+ _init4 = __decoratorStart();
1056
+ GuardRunnerService = __decorateElement(_init4, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
1057
+ __runInitializers(_init4, 1, GuardRunnerService);
1058
+ var _ModuleLoaderService_decorators, _init5;
1059
+ _ModuleLoaderService_decorators = [Injectable()];
1060
+ var _ModuleLoaderService = class _ModuleLoaderService {
1061
+ logger = inject(Logger, {
1062
+ context: _ModuleLoaderService.name
1063
+ });
1064
+ container = inject(Container);
1065
+ modulesMetadata = /* @__PURE__ */ new Map();
1066
+ loadedModules = /* @__PURE__ */ new Map();
1067
+ initialized = false;
1068
+ async loadModules(appModule) {
1069
+ if (this.initialized) {
1070
+ return;
1071
+ }
1072
+ await this.traverseModules(appModule);
1073
+ this.initialized = true;
1074
+ }
1075
+ async traverseModules(module, parentMetadata) {
1076
+ const metadata = extractModuleMetadata(module);
1077
+ if (parentMetadata) {
1078
+ this.mergeMetadata(metadata, parentMetadata);
1079
+ }
1080
+ const moduleName = module.name;
1081
+ if (this.modulesMetadata.has(moduleName)) {
1082
+ return;
1083
+ }
1084
+ this.modulesMetadata.set(moduleName, metadata);
1085
+ const imports = metadata.imports ?? /* @__PURE__ */ new Set();
1086
+ const loadingPromises = Array.from(imports).map(
1087
+ async (importedModule) => this.traverseModules(importedModule, metadata)
1088
+ );
1089
+ await Promise.all(loadingPromises);
1090
+ const instance = await this.container.get(module);
1091
+ if (instance.onModuleInit) {
1092
+ await instance.onModuleInit();
1093
+ }
1094
+ this.logger.debug(`Module ${moduleName} loaded`);
1095
+ this.loadedModules.set(moduleName, instance);
1096
+ }
1097
+ mergeMetadata(metadata, parentMetadata) {
1098
+ if (parentMetadata.guards) {
1099
+ for (const guard of parentMetadata.guards) {
1100
+ metadata.guards.add(guard);
1101
+ }
1102
+ }
1103
+ if (parentMetadata.customAttributes) {
1104
+ for (const [key, value] of parentMetadata.customAttributes) {
1105
+ if (metadata.customAttributes.has(key)) {
1106
+ continue;
1107
+ }
1108
+ metadata.customAttributes.set(key, value);
1109
+ }
1110
+ }
1111
+ }
1112
+ getAllModules() {
1113
+ return this.modulesMetadata;
1114
+ }
1115
+ dispose() {
1116
+ this.modulesMetadata.clear();
1117
+ this.loadedModules.clear();
1118
+ this.initialized = false;
1119
+ }
1120
+ };
1121
+ _init5 = __decoratorStart();
1122
+ _ModuleLoaderService = __decorateElement(_init5, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
1123
+ __runInitializers(_init5, 1, _ModuleLoaderService);
1124
+ var ModuleLoaderService = _ModuleLoaderService;
1125
+
1629
1126
  // src/attribute.factory.mts
1630
1127
  var AttributeFactory = class {
1631
1128
  static createAttribute(token, schema) {
@@ -1682,162 +1179,208 @@ var AttributeFactory = class {
1682
1179
  return target.customAttributes.has(attribute.token);
1683
1180
  }
1684
1181
  };
1685
- var _NaviosApplication_decorators, _init11;
1182
+ var _NaviosEnvironment_decorators, _init6;
1183
+ _NaviosEnvironment_decorators = [Injectable()];
1184
+ var NaviosEnvironment = class {
1185
+ httpTokens = /* @__PURE__ */ new Map();
1186
+ setupHttpEnvironment(tokens) {
1187
+ this.httpTokens = tokens;
1188
+ }
1189
+ getHttpToken(token) {
1190
+ return this.httpTokens.get(token);
1191
+ }
1192
+ hasHttpSetup() {
1193
+ return this.httpTokens.size > 0;
1194
+ }
1195
+ };
1196
+ _init6 = __decoratorStart();
1197
+ NaviosEnvironment = __decorateElement(_init6, 0, "NaviosEnvironment", _NaviosEnvironment_decorators, NaviosEnvironment);
1198
+ __runInitializers(_init6, 1, NaviosEnvironment);
1199
+
1200
+ // src/factories/endpoint-adapter.factory.mts
1201
+ var _EndpointAdapterFactory_decorators, _init7;
1202
+ _EndpointAdapterFactory_decorators = [Factory({
1203
+ token: EndpointAdapterToken
1204
+ })];
1205
+ var EndpointAdapterFactory = class {
1206
+ environment = inject(NaviosEnvironment);
1207
+ create(ctx) {
1208
+ const service = this.environment.getHttpToken(EndpointAdapterToken);
1209
+ if (!service) {
1210
+ throw new Error("EndpointAdapterToken service not found in environment");
1211
+ }
1212
+ return ctx.inject(service);
1213
+ }
1214
+ };
1215
+ _init7 = __decoratorStart();
1216
+ EndpointAdapterFactory = __decorateElement(_init7, 0, "EndpointAdapterFactory", _EndpointAdapterFactory_decorators, EndpointAdapterFactory);
1217
+ __runInitializers(_init7, 1, EndpointAdapterFactory);
1218
+ var _HttpAdapterFactory_decorators, _init8;
1219
+ _HttpAdapterFactory_decorators = [Factory({
1220
+ token: HttpAdapterToken
1221
+ })];
1222
+ var HttpAdapterFactory = class {
1223
+ environment = inject(NaviosEnvironment);
1224
+ create(ctx) {
1225
+ const service = this.environment.getHttpToken(HttpAdapterToken);
1226
+ if (!service) {
1227
+ throw new Error("HttpAdapterToken service not found in environment");
1228
+ }
1229
+ return ctx.inject(service);
1230
+ }
1231
+ };
1232
+ _init8 = __decoratorStart();
1233
+ HttpAdapterFactory = __decorateElement(_init8, 0, "HttpAdapterFactory", _HttpAdapterFactory_decorators, HttpAdapterFactory);
1234
+ __runInitializers(_init8, 1, HttpAdapterFactory);
1235
+ var _MultipartAdapterFactory_decorators, _init9;
1236
+ _MultipartAdapterFactory_decorators = [Factory({
1237
+ token: MultipartAdapterToken
1238
+ })];
1239
+ var MultipartAdapterFactory = class {
1240
+ environment = inject(NaviosEnvironment);
1241
+ create(ctx) {
1242
+ const service = this.environment.getHttpToken(MultipartAdapterToken);
1243
+ if (!service) {
1244
+ throw new Error("MultipartAdapterToken service not found in environment");
1245
+ }
1246
+ return ctx.inject(service);
1247
+ }
1248
+ };
1249
+ _init9 = __decoratorStart();
1250
+ MultipartAdapterFactory = __decorateElement(_init9, 0, "MultipartAdapterFactory", _MultipartAdapterFactory_decorators, MultipartAdapterFactory);
1251
+ __runInitializers(_init9, 1, MultipartAdapterFactory);
1252
+ var _RequestFactory_decorators, _init10;
1253
+ _RequestFactory_decorators = [Factory({
1254
+ token: Request,
1255
+ scope: InjectableScope.Request
1256
+ })];
1257
+ var RequestFactory = class {
1258
+ environment = inject(NaviosEnvironment);
1259
+ create(ctx) {
1260
+ const service = this.environment.getHttpToken(Request);
1261
+ if (!service) {
1262
+ throw new Error("RequestToken service not found in environment");
1263
+ }
1264
+ return ctx.inject(service);
1265
+ }
1266
+ };
1267
+ _init10 = __decoratorStart();
1268
+ RequestFactory = __decorateElement(_init10, 0, "RequestFactory", _RequestFactory_decorators, RequestFactory);
1269
+ __runInitializers(_init10, 1, RequestFactory);
1270
+ var _ReplyFactory_decorators, _init11;
1271
+ _ReplyFactory_decorators = [Factory({
1272
+ token: Reply,
1273
+ scope: InjectableScope.Request
1274
+ })];
1275
+ var ReplyFactory = class {
1276
+ environment = inject(NaviosEnvironment);
1277
+ create(ctx) {
1278
+ const service = this.environment.getHttpToken(Reply);
1279
+ if (!service) {
1280
+ throw new Error("ReplyToken service not found in environment");
1281
+ }
1282
+ return ctx.inject(service);
1283
+ }
1284
+ };
1285
+ _init11 = __decoratorStart();
1286
+ ReplyFactory = __decorateElement(_init11, 0, "ReplyFactory", _ReplyFactory_decorators, ReplyFactory);
1287
+ __runInitializers(_init11, 1, ReplyFactory);
1288
+ var _StreamAdapterFactory_decorators, _init12;
1289
+ _StreamAdapterFactory_decorators = [Factory({
1290
+ token: StreamAdapterToken
1291
+ })];
1292
+ var StreamAdapterFactory = class {
1293
+ environment = inject(NaviosEnvironment);
1294
+ create(ctx) {
1295
+ const service = this.environment.getHttpToken(StreamAdapterToken);
1296
+ if (!service) {
1297
+ throw new Error("StreamAdapterToken service not found in environment");
1298
+ }
1299
+ return ctx.inject(service);
1300
+ }
1301
+ };
1302
+ _init12 = __decoratorStart();
1303
+ StreamAdapterFactory = __decorateElement(_init12, 0, "StreamAdapterFactory", _StreamAdapterFactory_decorators, StreamAdapterFactory);
1304
+ __runInitializers(_init12, 1, StreamAdapterFactory);
1305
+ var _NaviosApplication_decorators, _init13;
1686
1306
  _NaviosApplication_decorators = [Injectable()];
1687
1307
  var _NaviosApplication = class _NaviosApplication {
1688
- moduleLoader = syncInject(ModuleLoaderService);
1689
- controllerAdapter = syncInject(ControllerAdapterService);
1690
- logger = syncInject(Logger, {
1308
+ environment = inject(NaviosEnvironment);
1309
+ moduleLoader = inject(ModuleLoaderService);
1310
+ httpApplication = null;
1311
+ logger = inject(Logger, {
1691
1312
  context: _NaviosApplication.name
1692
1313
  });
1693
- server = null;
1694
- corsOptions = null;
1695
- multipartOptions = null;
1696
- globalPrefix = null;
1314
+ container = inject(Container);
1697
1315
  appModule = null;
1698
- options = {};
1316
+ options = {
1317
+ adapter: []
1318
+ };
1699
1319
  isInitialized = false;
1700
- setup(appModule, options = {}) {
1320
+ async setup(appModule, options = {
1321
+ adapter: []
1322
+ }) {
1701
1323
  this.appModule = appModule;
1702
1324
  this.options = options;
1325
+ if (this.environment.hasHttpSetup()) {
1326
+ this.httpApplication = await this.container.get(HttpAdapterToken);
1327
+ }
1328
+ }
1329
+ getContainer() {
1330
+ return this.container;
1703
1331
  }
1704
1332
  async init() {
1705
1333
  if (!this.appModule) {
1706
1334
  throw new Error("App module is not set. Call setAppModule() first.");
1707
1335
  }
1708
1336
  await this.moduleLoader.loadModules(this.appModule);
1709
- this.server = await this.getFastifyInstance(this.options);
1710
- this.configureFastifyInstance(this.server);
1711
- getGlobalServiceLocator().storeInstance(this.server, Application);
1712
- this.server.setValidatorCompiler(validatorCompiler);
1713
- this.server.setSerializerCompiler(serializerCompiler);
1714
- if (this.corsOptions) {
1715
- await this.server.register(cors, this.corsOptions);
1716
- }
1717
- if (this.multipartOptions) {
1718
- await this.configureMultipart(this.server, this.multipartOptions);
1337
+ if (this.environment.hasHttpSetup()) {
1338
+ await this.httpApplication?.setupHttpServer(this.options);
1719
1339
  }
1720
1340
  await this.initModules();
1721
- await this.server.ready();
1341
+ if (this.environment.hasHttpSetup()) {
1342
+ await this.httpApplication?.ready();
1343
+ }
1722
1344
  this.isInitialized = true;
1723
1345
  this.logger.debug("Navios application initialized");
1724
1346
  }
1725
- async getFastifyInstance(rawOptions) {
1726
- const { logger, ...options } = rawOptions;
1727
- if (logger) {
1728
- const fastifyOptions = options;
1729
- if (typeof logger === "boolean") {
1730
- if (!logger) {
1731
- fastifyOptions.logger = false;
1732
- }
1733
- } else {
1734
- fastifyOptions.loggerInstance = new PinoWrapper(
1735
- await inject(Logger, {
1736
- context: "FastifyAdapter"
1737
- })
1738
- );
1739
- }
1740
- return fastify(fastifyOptions);
1741
- } else {
1742
- return fastify({
1743
- ...options,
1744
- loggerInstance: new PinoWrapper(
1745
- await inject(Logger, {
1746
- context: "FastifyAdapter"
1747
- })
1748
- )
1749
- });
1750
- }
1751
- }
1752
- configureFastifyInstance(fastifyInstance) {
1753
- fastifyInstance.setErrorHandler((error, request, reply) => {
1754
- if (error instanceof HttpException) {
1755
- return reply.status(error.statusCode).send(error.response);
1756
- } else {
1757
- const statusCode = error.statusCode || 500;
1758
- const message = error.message || "Internal Server Error";
1759
- const response = {
1760
- statusCode,
1761
- message,
1762
- error: error.name || "InternalServerError"
1763
- };
1764
- this.logger.error(
1765
- `Error occurred: ${error.message} on ${request.url}`,
1766
- error
1767
- );
1768
- return reply.status(statusCode).send(response);
1769
- }
1770
- });
1771
- fastifyInstance.setNotFoundHandler((req, reply) => {
1772
- const response = {
1773
- statusCode: 404,
1774
- message: "Not Found",
1775
- error: "NotFound"
1776
- };
1777
- this.logger.error(`Route not found: [${req.method}] ${req.url}`);
1778
- return reply.status(404).send(response);
1779
- });
1780
- }
1781
- async configureMultipart(server, options) {
1782
- if (options) {
1783
- await server.register(
1784
- multipart,
1785
- typeof options === "object" ? options : {}
1786
- );
1787
- }
1788
- }
1789
1347
  async initModules() {
1790
1348
  const modules = this.moduleLoader.getAllModules();
1791
- const promises = [];
1792
- for (const [moduleName, moduleMetadata] of modules) {
1793
- if (!moduleMetadata.controllers || moduleMetadata.controllers.size === 0) {
1794
- continue;
1795
- }
1796
- promises.push(
1797
- this.server.register(
1798
- async (instance, opts) => {
1799
- for (const controller of moduleMetadata.controllers) {
1800
- await this.controllerAdapter.setupController(
1801
- controller,
1802
- instance,
1803
- moduleMetadata
1804
- );
1805
- }
1806
- },
1807
- {
1808
- prefix: this.globalPrefix ?? ""
1809
- }
1810
- )
1811
- );
1812
- }
1813
- await Promise.all(promises);
1349
+ await this.httpApplication?.onModulesInit(modules);
1814
1350
  }
1815
1351
  enableCors(options) {
1816
- this.corsOptions = options;
1352
+ if (!this.httpApplication) {
1353
+ throw new Error("HTTP application is not set");
1354
+ }
1355
+ this.httpApplication.enableCors(options);
1817
1356
  }
1818
1357
  enableMultipart(options) {
1819
- this.multipartOptions = options;
1358
+ if (!this.httpApplication) {
1359
+ throw new Error("HTTP application is not set");
1360
+ }
1361
+ this.httpApplication.enableMultipart(options);
1820
1362
  }
1821
1363
  setGlobalPrefix(prefix) {
1822
- this.globalPrefix = prefix;
1364
+ if (!this.httpApplication) {
1365
+ throw new Error("HTTP application is not set");
1366
+ }
1367
+ this.httpApplication.setGlobalPrefix(prefix);
1823
1368
  }
1824
1369
  getServer() {
1825
- if (!this.server) {
1826
- throw new Error("Server is not initialized. Call init() first.");
1370
+ if (!this.httpApplication) {
1371
+ throw new Error("HTTP application is not set");
1827
1372
  }
1828
- return this.server;
1373
+ return this.httpApplication.getServer();
1829
1374
  }
1830
1375
  async listen(options) {
1831
- if (!this.server) {
1832
- throw new Error("Server is not initialized. Call init() first.");
1376
+ if (!this.httpApplication) {
1377
+ throw new Error("HTTP application is not set");
1833
1378
  }
1834
- const res = await this.server.listen(options);
1835
- this.logger.debug(`Navios is listening on ${res}`);
1379
+ await this.httpApplication.listen(options);
1836
1380
  }
1837
1381
  async dispose() {
1838
- if (this.server) {
1839
- await this.server.close();
1840
- this.server = null;
1382
+ if (this.httpApplication) {
1383
+ await this.httpApplication.dispose();
1841
1384
  }
1842
1385
  if (this.moduleLoader) {
1843
1386
  this.moduleLoader.dispose();
@@ -1847,28 +1390,52 @@ var _NaviosApplication = class _NaviosApplication {
1847
1390
  await this.dispose();
1848
1391
  }
1849
1392
  };
1850
- _init11 = __decoratorStart(null);
1851
- _NaviosApplication = __decorateElement(_init11, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
1852
- __runInitializers(_init11, 1, _NaviosApplication);
1393
+ _init13 = __decoratorStart();
1394
+ _NaviosApplication = __decorateElement(_init13, 0, "NaviosApplication", _NaviosApplication_decorators, _NaviosApplication);
1395
+ __runInitializers(_init13, 1, _NaviosApplication);
1853
1396
  var NaviosApplication = _NaviosApplication;
1854
1397
  var NaviosFactory = class {
1855
- static async create(appModule, options = {}) {
1856
- const app = await inject(NaviosApplication);
1857
- this.registerLoggerConfiguration(options);
1858
- app.setup(appModule, options);
1398
+ static async create(appModule, options = {
1399
+ adapter: []
1400
+ }) {
1401
+ const container = new Container();
1402
+ await this.registerLoggerConfiguration(container, options);
1403
+ const adapters = Array.isArray(options.adapter) ? options.adapter : [options.adapter];
1404
+ for (const adapter of adapters) {
1405
+ await this.registerEnvironment(container, adapter);
1406
+ }
1407
+ const app = await container.get(NaviosApplication);
1408
+ await app.setup(appModule, options);
1859
1409
  return app;
1860
1410
  }
1861
- static registerLoggerConfiguration(options) {
1862
- if (!options) {
1863
- return;
1411
+ static async registerEnvironment(container, environment = {}) {
1412
+ const naviosEnvironment = await container.get(NaviosEnvironment);
1413
+ const { httpTokens } = environment;
1414
+ if (httpTokens) {
1415
+ naviosEnvironment.setupHttpEnvironment(httpTokens);
1864
1416
  }
1417
+ }
1418
+ static async registerLoggerConfiguration(container, options) {
1865
1419
  const { logger } = options;
1420
+ if (Array.isArray(logger) || isNil(logger)) {
1421
+ const loggerInstance = await container.get(
1422
+ LoggerOutput
1423
+ );
1424
+ loggerInstance?.setup({
1425
+ logLevels: logger
1426
+ });
1427
+ }
1866
1428
  if (logger !== true && !isNil(logger)) {
1867
- LoggerInstance.overrideLogger(logger);
1429
+ container.getServiceLocator().getManager().storeCreatedHolder(
1430
+ LoggerOutput.toString(),
1431
+ logger,
1432
+ InjectableType.Class,
1433
+ InjectableScope.Singleton
1434
+ );
1868
1435
  }
1869
1436
  }
1870
1437
  };
1871
1438
 
1872
- export { Application, AttributeFactory, BadRequestException, ConfigProviderOptions, ConfigService, ConfigServiceOptionsSchema, ConfigServiceToken, ConflictException, ConsoleLogger, Controller, ControllerAdapterService, ControllerMetadataKey, Endpoint, EndpointAdapterService, EndpointAdapterToken, EndpointMetadataKey, EnvConfigProvider, ExecutionContext, ExecutionContextInjectionToken, ExecutionContextToken, ForbiddenException, GuardRunnerService, Header, HttpCode, HttpException, InternalServerErrorException, LOG_LEVELS, Logger, LoggerFactory, LoggerInjectionToken, LoggerInstance, LoggerOptions, Module, ModuleLoaderService, ModuleMetadataKey, Multipart, MultipartAdapterService, MultipartAdapterToken, NaviosApplication, NaviosFactory, NotFoundException, PinoWrapper, Reply, Request, Stream, StreamAdapterService, StreamAdapterToken, UnauthorizedException, UseGuards, addLeadingSlash, clc, envInt, envString, extractControllerMetadata, extractModuleMetadata, filterLogLevels, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getModuleMetadata, hasControllerMetadata, hasModuleMetadata, isConstructor, isEmpty, isFunction, isLogLevel, isLogLevelEnabled, isNil, isNumber, isObject, isPlainObject, isString, isSymbol, isUndefined, normalizePath, provideConfig, stripEndSlash, yellow };
1439
+ export { AttributeFactory, BadRequestException, ConfigProviderOptions, ConfigService, ConfigServiceOptionsSchema, ConfigServiceToken, ConflictException, ConsoleLogger, Controller, ControllerMetadataKey, Endpoint, EndpointAdapterFactory, EndpointAdapterToken, EndpointMetadataKey, EnvConfigProvider, ExecutionContext, ExecutionContextInjectionToken, ForbiddenException, GuardRunnerService, Header, HttpAdapterFactory, HttpAdapterToken, HttpCode, HttpException, InternalServerErrorException, LOG_LEVELS, Logger, LoggerInstance, LoggerOutput, Module, ModuleLoaderService, ModuleMetadataKey, Multipart, MultipartAdapterFactory, MultipartAdapterToken, NaviosApplication, NaviosFactory, NotFoundException, Reply, ReplyFactory, Request, RequestFactory, Stream, StreamAdapterFactory, StreamAdapterToken, UnauthorizedException, UseGuards, addLeadingSlash, clc, envInt, envString, extractControllerMetadata, extractModuleMetadata, filterLogLevels, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getModuleMetadata, hasControllerMetadata, hasModuleMetadata, isConstructor, isEmpty, isFunction, isLogLevel, isLogLevelEnabled, isNil, isNumber, isObject, isPlainObject, isString, isSymbol, isUndefined, loggerOptionsSchema, normalizePath, provideConfig, stripEndSlash, yellow };
1873
1440
  //# sourceMappingURL=index.mjs.map
1874
1441
  //# sourceMappingURL=index.mjs.map