@navios/core 0.1.12 → 0.1.14

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.
package/dist/index.mjs CHANGED
@@ -466,6 +466,7 @@ var ServiceLocator = class {
466
466
  destroyPromise: null,
467
467
  creationPromise: null
468
468
  });
469
+ this.eventBus.emit(instanceName, "create");
469
470
  }
470
471
  removeInstance(token) {
471
472
  const instanceName = this.getInstanceIdentifier(token, void 0);
@@ -1041,1469 +1042,1496 @@ function override(token, target) {
1041
1042
  };
1042
1043
  }
1043
1044
 
1044
- // packages/core/src/logger/console-logger.service.mts
1045
- var DEFAULT_DEPTH = 5;
1046
- var DEFAULT_LOG_LEVELS = [
1047
- "log",
1048
- "error",
1049
- "warn",
1050
- "debug",
1051
- "verbose",
1052
- "fatal"
1053
- ];
1054
- var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
1055
- year: "numeric",
1056
- hour: "numeric",
1057
- minute: "numeric",
1058
- second: "numeric",
1059
- day: "2-digit",
1060
- month: "2-digit"
1061
- });
1062
- var _ConsoleLogger_decorators, _init;
1063
- _ConsoleLogger_decorators = [Injectable()];
1064
- var _ConsoleLogger = class _ConsoleLogger {
1065
- /**
1066
- * The options of the logger.
1067
- */
1068
- options;
1069
- /**
1070
- * The context of the logger (can be set manually or automatically inferred).
1071
- */
1072
- context;
1073
- /**
1074
- * The original context of the logger (set in the constructor).
1075
- */
1076
- originalContext;
1077
- /**
1078
- * The options used for the "inspect" method.
1079
- */
1080
- inspectOptions;
1081
- /**
1082
- * The last timestamp at which the log message was printed.
1083
- */
1084
- static lastTimestampAt;
1085
- constructor(contextOrOptions, options) {
1086
- let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions == null ? void 0 : contextOrOptions.context, contextOrOptions];
1087
- opts = opts ?? {};
1088
- opts.logLevels ??= DEFAULT_LOG_LEVELS;
1089
- opts.colors ??= opts.colors ?? (opts.json ? false : true);
1090
- opts.prefix ??= "Navios";
1091
- this.options = opts;
1092
- this.inspectOptions = this.getInspectOptions();
1093
- if (context) {
1094
- this.context = context;
1095
- this.originalContext = context;
1045
+ // packages/core/src/tokens/application.token.mts
1046
+ var ApplicationInjectionToken = "ApplicationInjectionToken";
1047
+ var Application = InjectionToken.create(
1048
+ ApplicationInjectionToken
1049
+ );
1050
+
1051
+ // packages/core/src/services/controller-adapter.service.mts
1052
+ import { NaviosException as NaviosException3 } from "@navios/common";
1053
+ import { ZodArray } from "zod";
1054
+
1055
+ // packages/core/src/metadata/endpoint.metadata.mts
1056
+ var EndpointMetadataKey = Symbol("EndpointMetadataKey");
1057
+ var EndpointType = /* @__PURE__ */ ((EndpointType2) => {
1058
+ EndpointType2["Unknown"] = "unknown";
1059
+ EndpointType2["Endpoint"] = "endpoint";
1060
+ EndpointType2["Stream"] = "stream";
1061
+ EndpointType2["Multipart"] = "multipart";
1062
+ EndpointType2["Handler"] = "handler";
1063
+ return EndpointType2;
1064
+ })(EndpointType || {});
1065
+ function getAllEndpointMetadata(context) {
1066
+ if (context.metadata) {
1067
+ const metadata = context.metadata[EndpointMetadataKey];
1068
+ if (metadata) {
1069
+ return metadata;
1070
+ } else {
1071
+ context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
1072
+ return context.metadata[EndpointMetadataKey];
1096
1073
  }
1097
1074
  }
1098
- log(message, ...optionalParams) {
1099
- if (!this.isLevelEnabled("log")) {
1100
- return;
1075
+ throw new Error("[Navios] Wrong environment.");
1076
+ }
1077
+ function getEndpointMetadata(target, context) {
1078
+ if (context.metadata) {
1079
+ const metadata = getAllEndpointMetadata(context);
1080
+ if (metadata) {
1081
+ const endpointMetadata = Array.from(metadata).find(
1082
+ (item) => item.classMethod === target.name
1083
+ );
1084
+ if (endpointMetadata) {
1085
+ return endpointMetadata;
1086
+ } else {
1087
+ const newMetadata = {
1088
+ classMethod: target.name,
1089
+ url: "",
1090
+ successStatusCode: 200,
1091
+ headers: {},
1092
+ type: "unknown" /* Unknown */,
1093
+ httpMethod: "GET",
1094
+ config: null,
1095
+ guards: /* @__PURE__ */ new Set(),
1096
+ customAttributes: /* @__PURE__ */ new Map()
1097
+ };
1098
+ metadata.add(newMetadata);
1099
+ return newMetadata;
1100
+ }
1101
1101
  }
1102
- const { messages, context } = this.getContextAndMessagesToPrint([
1103
- message,
1104
- ...optionalParams
1105
- ]);
1106
- this.printMessages(messages, context, "log");
1107
1102
  }
1108
- error(message, ...optionalParams) {
1109
- if (!this.isLevelEnabled("error")) {
1110
- return;
1103
+ throw new Error("[Navios] Wrong environment.");
1104
+ }
1105
+
1106
+ // packages/core/src/metadata/controller.metadata.mts
1107
+ var ControllerMetadataKey = Symbol("ControllerMetadataKey");
1108
+ function getControllerMetadata(target, context) {
1109
+ if (context.metadata) {
1110
+ const metadata = context.metadata[ControllerMetadataKey];
1111
+ if (metadata) {
1112
+ return metadata;
1113
+ } else {
1114
+ const endpointsMetadata = getAllEndpointMetadata(context);
1115
+ const newMetadata = {
1116
+ endpoints: endpointsMetadata,
1117
+ guards: /* @__PURE__ */ new Set(),
1118
+ customAttributes: /* @__PURE__ */ new Map()
1119
+ };
1120
+ context.metadata[ControllerMetadataKey] = newMetadata;
1121
+ target[ControllerMetadataKey] = newMetadata;
1122
+ return newMetadata;
1111
1123
  }
1112
- const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
1113
- this.printMessages(messages, context, "error", "stderr", stack);
1114
- this.printStackTrace(stack);
1115
1124
  }
1116
- warn(message, ...optionalParams) {
1117
- if (!this.isLevelEnabled("warn")) {
1118
- return;
1119
- }
1120
- const { messages, context } = this.getContextAndMessagesToPrint([
1121
- message,
1122
- ...optionalParams
1123
- ]);
1124
- this.printMessages(messages, context, "warn");
1125
+ throw new Error("[Navios] Wrong environment.");
1126
+ }
1127
+ function extractControllerMetadata(target) {
1128
+ const metadata = target[ControllerMetadataKey];
1129
+ if (!metadata) {
1130
+ throw new Error(
1131
+ "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
1132
+ );
1125
1133
  }
1126
- debug(message, ...optionalParams) {
1127
- if (!this.isLevelEnabled("debug")) {
1128
- return;
1134
+ return metadata;
1135
+ }
1136
+ function hasControllerMetadata(target) {
1137
+ const metadata = target[ControllerMetadataKey];
1138
+ return !!metadata;
1139
+ }
1140
+
1141
+ // packages/core/src/metadata/module.metadata.mts
1142
+ var ModuleMetadataKey = Symbol("ControllerMetadataKey");
1143
+ function getModuleMetadata(target, context) {
1144
+ if (context.metadata) {
1145
+ const metadata = context.metadata[ModuleMetadataKey];
1146
+ if (metadata) {
1147
+ return metadata;
1148
+ } else {
1149
+ const newMetadata = {
1150
+ controllers: /* @__PURE__ */ new Set(),
1151
+ imports: /* @__PURE__ */ new Set(),
1152
+ guards: /* @__PURE__ */ new Set(),
1153
+ customAttributes: /* @__PURE__ */ new Map()
1154
+ };
1155
+ context.metadata[ModuleMetadataKey] = newMetadata;
1156
+ target[ModuleMetadataKey] = newMetadata;
1157
+ return newMetadata;
1129
1158
  }
1130
- const { messages, context } = this.getContextAndMessagesToPrint([
1131
- message,
1132
- ...optionalParams
1133
- ]);
1134
- this.printMessages(messages, context, "debug");
1135
1159
  }
1136
- verbose(message, ...optionalParams) {
1137
- if (!this.isLevelEnabled("verbose")) {
1138
- return;
1139
- }
1140
- const { messages, context } = this.getContextAndMessagesToPrint([
1141
- message,
1142
- ...optionalParams
1143
- ]);
1144
- this.printMessages(messages, context, "verbose");
1160
+ throw new Error("[Navios] Wrong environment.");
1161
+ }
1162
+ function extractModuleMetadata(target) {
1163
+ const metadata = target[ModuleMetadataKey];
1164
+ if (!metadata) {
1165
+ throw new Error(
1166
+ `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
1167
+ );
1145
1168
  }
1146
- fatal(message, ...optionalParams) {
1147
- if (!this.isLevelEnabled("fatal")) {
1148
- return;
1149
- }
1150
- const { messages, context } = this.getContextAndMessagesToPrint([
1151
- message,
1152
- ...optionalParams
1153
- ]);
1154
- this.printMessages(messages, context, "fatal");
1169
+ return metadata;
1170
+ }
1171
+ function hasModuleMetadata(target) {
1172
+ return !!target[ModuleMetadataKey];
1173
+ }
1174
+
1175
+ // packages/core/src/services/execution-context.mts
1176
+ var ExecutionContext = class {
1177
+ constructor(module, controller, handler) {
1178
+ this.module = module;
1179
+ this.controller = controller;
1180
+ this.handler = handler;
1155
1181
  }
1156
- /**
1157
- * Set log levels
1158
- * @param levels log levels
1159
- */
1160
- setLogLevels(levels) {
1161
- if (!this.options) {
1162
- this.options = {};
1163
- }
1164
- this.options.logLevels = levels;
1182
+ request;
1183
+ reply;
1184
+ getModule() {
1185
+ return this.module;
1165
1186
  }
1166
- /**
1167
- * Set logger context
1168
- * @param context context
1169
- */
1170
- setContext(context) {
1171
- this.context = context;
1187
+ getController() {
1188
+ return this.controller;
1172
1189
  }
1173
- /**
1174
- * Resets the logger context to the value that was passed in the constructor.
1175
- */
1176
- resetContext() {
1177
- this.context = this.originalContext;
1190
+ getHandler() {
1191
+ return this.handler;
1178
1192
  }
1179
- isLevelEnabled(level) {
1180
- var _a;
1181
- const logLevels = (_a = this.options) == null ? void 0 : _a.logLevels;
1182
- return isLogLevelEnabled(level, logLevels);
1183
- }
1184
- getTimestamp() {
1185
- return dateTimeFormatter.format(Date.now());
1186
- }
1187
- printMessages(messages, context = "", logLevel = "log", writeStreamType, errorStack) {
1188
- messages.forEach((message) => {
1189
- if (this.options.json) {
1190
- this.printAsJson(message, {
1191
- context,
1192
- logLevel,
1193
- writeStreamType,
1194
- errorStack
1195
- });
1196
- return;
1197
- }
1198
- const pidMessage = this.formatPid(process.pid);
1199
- const contextMessage = this.formatContext(context);
1200
- const timestampDiff = this.updateAndGetTimestampDiff();
1201
- const formattedLogLevel = logLevel.toUpperCase().padStart(7, " ");
1202
- const formattedMessage = this.formatMessage(
1203
- logLevel,
1204
- message,
1205
- pidMessage,
1206
- formattedLogLevel,
1207
- contextMessage,
1208
- timestampDiff
1193
+ getRequest() {
1194
+ if (!this.request) {
1195
+ throw new Error(
1196
+ "[Navios] Request is not set. Make sure to set it before using it."
1209
1197
  );
1210
- process[writeStreamType ?? "stdout"].write(formattedMessage);
1211
- });
1212
- }
1213
- printAsJson(message, options) {
1214
- const logObject = {
1215
- level: options.logLevel,
1216
- pid: process.pid,
1217
- timestamp: Date.now(),
1218
- message
1219
- };
1220
- if (options.context) {
1221
- logObject.context = options.context;
1222
1198
  }
1223
- if (options.errorStack) {
1224
- logObject.stack = options.errorStack;
1199
+ return this.request;
1200
+ }
1201
+ getReply() {
1202
+ if (!this.reply) {
1203
+ throw new Error(
1204
+ "[Navios] Reply is not set. Make sure to set it before using it."
1205
+ );
1225
1206
  }
1226
- const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : inspect(logObject, this.inspectOptions);
1227
- process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
1228
- `);
1207
+ return this.reply;
1229
1208
  }
1230
- formatPid(pid) {
1231
- return `[${this.options.prefix}] ${pid} - `;
1209
+ provideRequest(request) {
1210
+ this.request = request;
1232
1211
  }
1233
- formatContext(context) {
1234
- if (!context) {
1235
- return "";
1236
- }
1237
- context = `[${context}] `;
1238
- return this.options.colors ? yellow(context) : context;
1212
+ provideReply(reply) {
1213
+ this.reply = reply;
1239
1214
  }
1240
- formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
1241
- const output = this.stringifyMessage(message, logLevel);
1242
- pidMessage = this.colorize(pidMessage, logLevel);
1243
- formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
1244
- return `${pidMessage}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
1245
- `;
1215
+ };
1216
+
1217
+ // packages/core/src/exceptions/http.exception.mts
1218
+ var HttpException = class {
1219
+ constructor(statusCode, response, error) {
1220
+ this.statusCode = statusCode;
1221
+ this.response = response;
1222
+ this.error = error;
1246
1223
  }
1247
- stringifyMessage(message, logLevel) {
1248
- if (isFunction(message)) {
1249
- const messageAsStr = Function.prototype.toString.call(message);
1250
- const isClass = messageAsStr.startsWith("class ");
1251
- if (isClass) {
1252
- return this.stringifyMessage(message.name, logLevel);
1253
- }
1254
- return this.stringifyMessage(message(), logLevel);
1255
- }
1256
- if (typeof message === "string") {
1257
- return this.colorize(message, logLevel);
1258
- }
1259
- const outputText = inspect(message, this.inspectOptions);
1260
- if (isPlainObject(message)) {
1261
- return `Object(${Object.keys(message).length}) ${outputText}`;
1262
- }
1263
- if (Array.isArray(message)) {
1264
- return `Array(${message.length}) ${outputText}`;
1265
- }
1266
- return outputText;
1224
+ };
1225
+
1226
+ // packages/core/src/exceptions/bad-request.exception.mts
1227
+ var BadRequestException = class extends HttpException {
1228
+ constructor(message) {
1229
+ super(400, message);
1267
1230
  }
1268
- colorize(message, logLevel) {
1269
- if (!this.options.colors || this.options.json) {
1270
- return message;
1271
- }
1272
- const color = this.getColorByLogLevel(logLevel);
1273
- return color(message);
1231
+ };
1232
+
1233
+ // packages/core/src/exceptions/forbidden.exception.mts
1234
+ var ForbiddenException = class extends HttpException {
1235
+ constructor(message) {
1236
+ super(403, message);
1274
1237
  }
1275
- printStackTrace(stack) {
1276
- if (!stack || this.options.json) {
1277
- return;
1278
- }
1279
- process.stderr.write(`${stack}
1280
- `);
1238
+ };
1239
+
1240
+ // packages/core/src/exceptions/internal-server-error.exception.mts
1241
+ var InternalServerErrorException = class extends HttpException {
1242
+ constructor(message, error) {
1243
+ super(500, message, error);
1281
1244
  }
1282
- updateAndGetTimestampDiff() {
1283
- var _a;
1284
- const includeTimestamp = _ConsoleLogger.lastTimestampAt && ((_a = this.options) == null ? void 0 : _a.timestamp);
1285
- const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
1286
- _ConsoleLogger.lastTimestampAt = Date.now();
1287
- return result;
1245
+ };
1246
+
1247
+ // packages/core/src/exceptions/not-found.exception.mts
1248
+ var NotFoundException = class extends HttpException {
1249
+ constructor(response, error) {
1250
+ super(404, response, error);
1251
+ this.response = response;
1252
+ this.error = error;
1288
1253
  }
1289
- formatTimestampDiff(timestampDiff) {
1290
- const formattedDiff = ` +${timestampDiff}ms`;
1291
- return this.options.colors ? yellow(formattedDiff) : formattedDiff;
1254
+ };
1255
+
1256
+ // packages/core/src/exceptions/unauthorized.exception.mts
1257
+ var UnauthorizedException = class extends HttpException {
1258
+ constructor(message, error) {
1259
+ super(401, message, error);
1292
1260
  }
1293
- getInspectOptions() {
1294
- let breakLength = this.options.breakLength;
1295
- if (typeof breakLength === "undefined") {
1296
- breakLength = this.options.colors ? this.options.compact ? Infinity : void 0 : this.options.compact === false ? void 0 : Infinity;
1297
- }
1298
- const inspectOptions = {
1299
- depth: this.options.depth ?? DEFAULT_DEPTH,
1300
- sorted: this.options.sorted,
1301
- showHidden: this.options.showHidden,
1302
- compact: this.options.compact ?? (this.options.json ? true : false),
1303
- colors: this.options.colors,
1304
- breakLength
1305
- };
1306
- if (this.options.maxArrayLength) {
1307
- inspectOptions.maxArrayLength = this.options.maxArrayLength;
1261
+ };
1262
+
1263
+ // packages/core/src/exceptions/conflict.exception.mts
1264
+ var ConflictException = class extends HttpException {
1265
+ constructor(message, error) {
1266
+ super(409, message, error);
1267
+ }
1268
+ };
1269
+
1270
+ // packages/core/src/services/guard-runner.service.mts
1271
+ var _GuardRunnerService_decorators, _init;
1272
+ _GuardRunnerService_decorators = [Injectable()];
1273
+ var GuardRunnerService = class {
1274
+ async runGuards(allGuards, executionContext) {
1275
+ let canActivate = true;
1276
+ for (const guard of Array.from(allGuards).reverse()) {
1277
+ const guardInstance = await inject(
1278
+ guard
1279
+ );
1280
+ if (!guardInstance.canActivate) {
1281
+ throw new Error(
1282
+ `[Navios] Guard ${guard.name} does not implement canActivate()`
1283
+ );
1284
+ }
1285
+ try {
1286
+ canActivate = await guardInstance.canActivate(executionContext);
1287
+ if (!canActivate) {
1288
+ break;
1289
+ }
1290
+ } catch (error) {
1291
+ if (error instanceof HttpException) {
1292
+ executionContext.getReply().status(error.statusCode).send(error.response);
1293
+ return false;
1294
+ } else {
1295
+ executionContext.getReply().status(500).send({
1296
+ message: "Internal server error",
1297
+ error: error.message
1298
+ });
1299
+ return false;
1300
+ }
1301
+ }
1308
1302
  }
1309
- if (this.options.maxStringLength) {
1310
- inspectOptions.maxStringLength = this.options.maxStringLength;
1303
+ if (!canActivate) {
1304
+ executionContext.getReply().status(403).send({
1305
+ message: "Forbidden"
1306
+ });
1307
+ return false;
1311
1308
  }
1312
- return inspectOptions;
1309
+ return canActivate;
1313
1310
  }
1314
- stringifyReplacer(key, value) {
1315
- if (typeof value === "bigint") {
1316
- return value.toString();
1311
+ makeContext(executionContext) {
1312
+ const guards = /* @__PURE__ */ new Set();
1313
+ const endpointGuards = executionContext.getHandler().guards;
1314
+ const controllerGuards = executionContext.getController().guards;
1315
+ const moduleGuards = executionContext.getModule().guards;
1316
+ if (endpointGuards.size > 0) {
1317
+ for (const guard of endpointGuards) {
1318
+ guards.add(guard);
1319
+ }
1317
1320
  }
1318
- if (typeof value === "symbol") {
1319
- return value.toString();
1321
+ if (controllerGuards.size > 0) {
1322
+ for (const guard of controllerGuards) {
1323
+ guards.add(guard);
1324
+ }
1320
1325
  }
1321
- if (value instanceof Map || value instanceof Set || value instanceof Error) {
1322
- return `${inspect(value, this.inspectOptions)}`;
1323
- }
1324
- return value;
1325
- }
1326
- getContextAndMessagesToPrint(args) {
1327
- if ((args == null ? void 0 : args.length) <= 1) {
1328
- return { messages: args, context: this.context };
1329
- }
1330
- const lastElement = args[args.length - 1];
1331
- const isContext = isString(lastElement);
1332
- if (!isContext) {
1333
- return { messages: args, context: this.context };
1334
- }
1335
- return {
1336
- context: lastElement,
1337
- messages: args.slice(0, args.length - 1)
1338
- };
1339
- }
1340
- getContextAndStackAndMessagesToPrint(args) {
1341
- if (args.length === 2) {
1342
- return this.isStackFormat(args[1]) ? {
1343
- messages: [args[0]],
1344
- stack: args[1],
1345
- context: this.context
1346
- } : {
1347
- messages: [args[0]],
1348
- context: args[1]
1349
- };
1350
- }
1351
- const { messages, context } = this.getContextAndMessagesToPrint(args);
1352
- if ((messages == null ? void 0 : messages.length) <= 1) {
1353
- return { messages, context };
1354
- }
1355
- const lastElement = messages[messages.length - 1];
1356
- const isStack = isString(lastElement);
1357
- if (!isStack && !isUndefined(lastElement)) {
1358
- return { messages, context };
1359
- }
1360
- return {
1361
- stack: lastElement,
1362
- messages: messages.slice(0, messages.length - 1),
1363
- context
1364
- };
1365
- }
1366
- isStackFormat(stack) {
1367
- if (!isString(stack) && !isUndefined(stack)) {
1368
- return false;
1369
- }
1370
- return /^(.)+\n\s+at .+:\d+:\d+/.test(stack);
1371
- }
1372
- getColorByLogLevel(level) {
1373
- switch (level) {
1374
- case "debug":
1375
- return clc.magentaBright;
1376
- case "warn":
1377
- return clc.yellow;
1378
- case "error":
1379
- return clc.red;
1380
- case "verbose":
1381
- return clc.cyanBright;
1382
- case "fatal":
1383
- return clc.bold;
1384
- default:
1385
- return clc.green;
1326
+ if (moduleGuards.size > 0) {
1327
+ for (const guard of moduleGuards) {
1328
+ guards.add(guard);
1329
+ }
1386
1330
  }
1331
+ return guards;
1387
1332
  }
1388
1333
  };
1389
1334
  _init = __decoratorStart(null);
1390
- _ConsoleLogger = __decorateElement(_init, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
1391
- __runInitializers(_init, 1, _ConsoleLogger);
1392
- var ConsoleLogger = _ConsoleLogger;
1393
-
1394
- // packages/core/src/logger/logger.factory.mts
1395
- import { z as z2 } from "zod";
1335
+ GuardRunnerService = __decorateElement(_init, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
1336
+ __runInitializers(_init, 1, GuardRunnerService);
1396
1337
 
1397
- // packages/core/src/logger/logger.service.mts
1398
- var DEFAULT_LOGGER = new ConsoleLogger();
1399
- var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
1400
- year: "numeric",
1401
- hour: "numeric",
1402
- minute: "numeric",
1403
- second: "numeric",
1404
- day: "2-digit",
1405
- month: "2-digit"
1406
- });
1407
- var _LoggerInstance_decorators, _init2;
1408
- _LoggerInstance_decorators = [Injectable()];
1409
- var _LoggerInstance = class _LoggerInstance {
1410
- constructor(context, options = {}) {
1411
- this.context = context;
1412
- this.options = options;
1413
- }
1414
- static staticInstanceRef = DEFAULT_LOGGER;
1415
- static logLevels;
1416
- localInstanceRef;
1417
- get localInstance() {
1418
- if (_LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {
1419
- return this.registerLocalInstanceRef();
1420
- } else if (_LoggerInstance.staticInstanceRef instanceof _LoggerInstance) {
1421
- const prototype = Object.getPrototypeOf(_LoggerInstance.staticInstanceRef);
1422
- if (prototype.constructor === _LoggerInstance) {
1423
- return this.registerLocalInstanceRef();
1338
+ // packages/core/src/services/controller-adapter.service.mts
1339
+ var _ControllerAdapterService_decorators, _init2;
1340
+ _ControllerAdapterService_decorators = [Injectable()];
1341
+ var _ControllerAdapterService = class _ControllerAdapterService {
1342
+ guardRunner = syncInject(GuardRunnerService);
1343
+ logger = syncInject(Logger, {
1344
+ context: _ControllerAdapterService.name
1345
+ });
1346
+ setupController(controller, instance, moduleMetadata) {
1347
+ const controllerMetadata = extractControllerMetadata(controller);
1348
+ for (const endpoint of controllerMetadata.endpoints) {
1349
+ const { classMethod, url, httpMethod } = endpoint;
1350
+ if (!url) {
1351
+ throw new Error(
1352
+ `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
1353
+ );
1424
1354
  }
1355
+ const executionContext = new ExecutionContext(
1356
+ moduleMetadata,
1357
+ controllerMetadata,
1358
+ endpoint
1359
+ );
1360
+ instance.withTypeProvider().route({
1361
+ method: httpMethod,
1362
+ url: url.replaceAll("$", ":"),
1363
+ schema: this.provideSchemaForConfig(endpoint),
1364
+ preHandler: this.providePreHandler(executionContext),
1365
+ handler: this.provideHandler(controller, executionContext, endpoint)
1366
+ });
1367
+ this.logger.debug(
1368
+ `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
1369
+ );
1425
1370
  }
1426
- return _LoggerInstance.staticInstanceRef;
1427
- }
1428
- error(message, ...optionalParams) {
1429
- var _a;
1430
- optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
1431
- this.context
1432
- ) : optionalParams;
1433
- (_a = this.localInstance) == null ? void 0 : _a.error(message, ...optionalParams);
1434
- }
1435
- log(message, ...optionalParams) {
1436
- var _a;
1437
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1438
- (_a = this.localInstance) == null ? void 0 : _a.log(message, ...optionalParams);
1439
- }
1440
- warn(message, ...optionalParams) {
1441
- var _a;
1442
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1443
- (_a = this.localInstance) == null ? void 0 : _a.warn(message, ...optionalParams);
1444
- }
1445
- debug(message, ...optionalParams) {
1446
- var _a, _b;
1447
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1448
- (_b = (_a = this.localInstance) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1449
- }
1450
- verbose(message, ...optionalParams) {
1451
- var _a, _b;
1452
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1453
- (_b = (_a = this.localInstance) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1454
1371
  }
1455
- fatal(message, ...optionalParams) {
1456
- var _a, _b;
1457
- optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
1458
- (_b = (_a = this.localInstance) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1459
- }
1460
- static error(message, ...optionalParams) {
1461
- var _a;
1462
- (_a = this.staticInstanceRef) == null ? void 0 : _a.error(message, ...optionalParams);
1372
+ providePreHandler(executionContext) {
1373
+ const guards = this.guardRunner.makeContext(executionContext);
1374
+ return guards.size > 0 ? async (request, reply) => {
1375
+ getServiceLocator().registerInstance(Request, request);
1376
+ getServiceLocator().registerInstance(Reply, reply);
1377
+ getServiceLocator().registerInstance(
1378
+ ExecutionContextToken,
1379
+ executionContext
1380
+ );
1381
+ executionContext.provideRequest(request);
1382
+ executionContext.provideReply(reply);
1383
+ let canActivate = true;
1384
+ try {
1385
+ canActivate = await this.guardRunner.runGuards(
1386
+ guards,
1387
+ executionContext
1388
+ );
1389
+ } finally {
1390
+ getServiceLocator().removeInstance(Request);
1391
+ getServiceLocator().removeInstance(Reply);
1392
+ getServiceLocator().removeInstance(ExecutionContextToken);
1393
+ }
1394
+ if (!canActivate) {
1395
+ return reply;
1396
+ }
1397
+ } : void 0;
1463
1398
  }
1464
- static log(message, ...optionalParams) {
1465
- var _a;
1466
- (_a = this.staticInstanceRef) == null ? void 0 : _a.log(message, ...optionalParams);
1399
+ provideSchemaForConfig(endpointMetadata) {
1400
+ if (!endpointMetadata.config) {
1401
+ this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`);
1402
+ return {};
1403
+ }
1404
+ const { querySchema, requestSchema, responseSchema } = endpointMetadata.config;
1405
+ const schema = {};
1406
+ if (querySchema) {
1407
+ schema.querystring = querySchema;
1408
+ }
1409
+ if (requestSchema && endpointMetadata.type !== "multipart" /* Multipart */) {
1410
+ schema.body = requestSchema;
1411
+ }
1412
+ if (responseSchema) {
1413
+ schema.response = {
1414
+ 200: responseSchema
1415
+ };
1416
+ }
1417
+ return schema;
1467
1418
  }
1468
- static warn(message, ...optionalParams) {
1469
- var _a;
1470
- (_a = this.staticInstanceRef) == null ? void 0 : _a.warn(message, ...optionalParams);
1419
+ provideHandler(controller, executionContext, endpointMetadata) {
1420
+ switch (endpointMetadata.type) {
1421
+ case "unknown" /* Unknown */:
1422
+ this.logger.error(
1423
+ `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`
1424
+ );
1425
+ throw new NaviosException3("Unknown endpoint type");
1426
+ case "endpoint" /* Endpoint */:
1427
+ return this.provideHandlerForConfig(
1428
+ controller,
1429
+ executionContext,
1430
+ endpointMetadata
1431
+ );
1432
+ case "stream" /* Stream */:
1433
+ return this.provideHandlerForStream(
1434
+ controller,
1435
+ executionContext,
1436
+ endpointMetadata
1437
+ );
1438
+ case "multipart" /* Multipart */:
1439
+ return this.provideHandlerForMultipart(
1440
+ controller,
1441
+ executionContext,
1442
+ endpointMetadata
1443
+ );
1444
+ case "handler" /* Handler */:
1445
+ this.logger.error("Not implemented yet");
1446
+ throw new NaviosException3("Not implemented yet");
1447
+ }
1471
1448
  }
1472
- static debug(message, ...optionalParams) {
1473
- var _a, _b;
1474
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1449
+ provideHandlerForConfig(controller, executionContext, endpointMetadata) {
1450
+ return async (request, reply) => {
1451
+ getServiceLocator().registerInstance(Request, request);
1452
+ getServiceLocator().registerInstance(Reply, reply);
1453
+ getServiceLocator().registerInstance(
1454
+ ExecutionContextToken,
1455
+ executionContext
1456
+ );
1457
+ executionContext.provideRequest(request);
1458
+ executionContext.provideReply(reply);
1459
+ const controllerInstance = await inject(controller);
1460
+ try {
1461
+ const { query, params, body } = request;
1462
+ const argument = {};
1463
+ if (query && Object.keys(query).length > 0) {
1464
+ argument.params = query;
1465
+ }
1466
+ if (params && Object.keys(params).length > 0) {
1467
+ argument.urlParams = params;
1468
+ }
1469
+ if (body) {
1470
+ argument.data = body;
1471
+ }
1472
+ const result = await controllerInstance[endpointMetadata.classMethod](argument);
1473
+ reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
1474
+ } finally {
1475
+ getServiceLocator().removeInstance(Request);
1476
+ getServiceLocator().removeInstance(Reply);
1477
+ getServiceLocator().removeInstance(ExecutionContextToken);
1478
+ }
1479
+ };
1475
1480
  }
1476
- static verbose(message, ...optionalParams) {
1477
- var _a, _b;
1478
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1481
+ provideHandlerForStream(controller, executionContext, endpointMetadata) {
1482
+ return async (request, reply) => {
1483
+ getServiceLocator().registerInstance(Request, request);
1484
+ getServiceLocator().registerInstance(Reply, reply);
1485
+ getServiceLocator().registerInstance(
1486
+ ExecutionContextToken,
1487
+ executionContext
1488
+ );
1489
+ executionContext.provideRequest(request);
1490
+ executionContext.provideReply(reply);
1491
+ const controllerInstance = await inject(controller);
1492
+ try {
1493
+ const { query, params, body } = request;
1494
+ const argument = {};
1495
+ if (query && Object.keys(query).length > 0) {
1496
+ argument.params = query;
1497
+ }
1498
+ if (params && Object.keys(params).length > 0) {
1499
+ argument.urlParams = params;
1500
+ }
1501
+ if (body) {
1502
+ argument.data = body;
1503
+ }
1504
+ await controllerInstance[endpointMetadata.classMethod](argument, reply);
1505
+ } finally {
1506
+ getServiceLocator().removeInstance(Request);
1507
+ getServiceLocator().removeInstance(Reply);
1508
+ getServiceLocator().removeInstance(ExecutionContextToken);
1509
+ }
1510
+ };
1479
1511
  }
1480
- static fatal(message, ...optionalParams) {
1481
- var _a, _b;
1482
- (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1512
+ provideHandlerForMultipart(controller, executionContext, endpointMetadata) {
1513
+ const config = endpointMetadata.config;
1514
+ const requestSchema = config.requestSchema;
1515
+ const shape = requestSchema._def.shape();
1516
+ return async (request, reply) => {
1517
+ getServiceLocator().registerInstance(Request, request);
1518
+ getServiceLocator().registerInstance(Reply, reply);
1519
+ getServiceLocator().registerInstance(
1520
+ ExecutionContextToken,
1521
+ executionContext
1522
+ );
1523
+ executionContext.provideRequest(request);
1524
+ executionContext.provideReply(reply);
1525
+ const controllerInstance = await inject(controller);
1526
+ try {
1527
+ const parts = request.parts();
1528
+ const { query, params } = request;
1529
+ const argument = {};
1530
+ if (query && Object.keys(query).length > 0) {
1531
+ argument.params = query;
1532
+ }
1533
+ if (params && Object.keys(params).length > 0) {
1534
+ argument.urlParams = params;
1535
+ }
1536
+ const req = {};
1537
+ for await (const part of parts) {
1538
+ if (!shape[part.fieldname]) {
1539
+ throw new NaviosException3(
1540
+ `Invalid field name ${part.fieldname} for multipart request`
1541
+ );
1542
+ }
1543
+ const schema = shape[part.fieldname];
1544
+ if (part.type === "file") {
1545
+ const file = new File([await part.toBuffer()], part.filename, {
1546
+ type: part.mimetype
1547
+ });
1548
+ if (schema instanceof ZodArray) {
1549
+ if (!req[part.fieldname]) {
1550
+ req[part.fieldname] = [];
1551
+ }
1552
+ req[part.fieldname].push(file);
1553
+ } else {
1554
+ req[part.fieldname] = file;
1555
+ }
1556
+ } else {
1557
+ if (schema instanceof ZodArray) {
1558
+ if (!req[part.fieldname]) {
1559
+ req[part.fieldname] = [];
1560
+ }
1561
+ req[part.fieldname].push(part.value);
1562
+ } else {
1563
+ req[part.fieldname] = part.value;
1564
+ }
1565
+ }
1566
+ }
1567
+ argument.data = requestSchema.parse(req);
1568
+ const result = await controllerInstance[endpointMetadata.classMethod](argument);
1569
+ reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
1570
+ } finally {
1571
+ getServiceLocator().removeInstance(Request);
1572
+ getServiceLocator().removeInstance(Reply);
1573
+ getServiceLocator().removeInstance(ExecutionContextToken);
1574
+ }
1575
+ };
1483
1576
  }
1484
- static getTimestamp() {
1485
- return dateTimeFormatter2.format(Date.now());
1577
+ };
1578
+ _init2 = __decoratorStart(null);
1579
+ _ControllerAdapterService = __decorateElement(_init2, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
1580
+ __runInitializers(_init2, 1, _ControllerAdapterService);
1581
+ var ControllerAdapterService = _ControllerAdapterService;
1582
+
1583
+ // packages/core/src/services/module-loader.service.mts
1584
+ var _ModuleLoaderService_decorators, _init3;
1585
+ _ModuleLoaderService_decorators = [Injectable()];
1586
+ var _ModuleLoaderService = class _ModuleLoaderService {
1587
+ logger = syncInject(Logger, {
1588
+ context: _ModuleLoaderService.name
1589
+ });
1590
+ modulesMetadata = /* @__PURE__ */ new Map();
1591
+ loadedModules = /* @__PURE__ */ new Map();
1592
+ initialized = false;
1593
+ async loadModules(appModule) {
1594
+ if (this.initialized) {
1595
+ return;
1596
+ }
1597
+ await this.traverseModules(appModule);
1598
+ this.initialized = true;
1486
1599
  }
1487
- static overrideLogger(logger) {
1488
- var _a, _b;
1489
- if (Array.isArray(logger)) {
1490
- _LoggerInstance.logLevels = logger;
1491
- return (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.setLogLevels) == null ? void 0 : _b.call(_a, logger);
1600
+ async traverseModules(module, parentMetadata) {
1601
+ const metadata = extractModuleMetadata(module);
1602
+ if (parentMetadata) {
1603
+ this.mergeMetadata(metadata, parentMetadata);
1492
1604
  }
1493
- if (isObject(logger)) {
1494
- this.staticInstanceRef = logger;
1495
- } else {
1496
- this.staticInstanceRef = void 0;
1605
+ const moduleName = module.name;
1606
+ if (this.modulesMetadata.has(moduleName)) {
1607
+ return;
1497
1608
  }
1609
+ this.modulesMetadata.set(moduleName, metadata);
1610
+ const imports = metadata.imports ?? /* @__PURE__ */ new Set();
1611
+ const loadingPromises = Array.from(imports).map(
1612
+ async (importedModule) => this.traverseModules(importedModule, metadata)
1613
+ );
1614
+ await Promise.all(loadingPromises);
1615
+ const instance = await inject(module);
1616
+ if (instance.onModuleInit) {
1617
+ await instance.onModuleInit();
1618
+ }
1619
+ this.logger.debug(`Module ${moduleName} loaded`);
1620
+ this.loadedModules.set(moduleName, instance);
1498
1621
  }
1499
- static isLevelEnabled(level) {
1500
- const logLevels = _LoggerInstance.logLevels;
1501
- return isLogLevelEnabled(level, logLevels);
1502
- }
1503
- registerLocalInstanceRef() {
1504
- var _a;
1505
- if (this.localInstanceRef) {
1506
- return this.localInstanceRef;
1622
+ mergeMetadata(metadata, parentMetadata) {
1623
+ if (parentMetadata.guards) {
1624
+ for (const guard of parentMetadata.guards) {
1625
+ metadata.guards.add(guard);
1626
+ }
1627
+ }
1628
+ if (parentMetadata.customAttributes) {
1629
+ for (const [key, value] of parentMetadata.customAttributes) {
1630
+ if (metadata.customAttributes.has(key)) {
1631
+ continue;
1632
+ }
1633
+ metadata.customAttributes.set(key, value);
1634
+ }
1507
1635
  }
1508
- this.localInstanceRef = new ConsoleLogger(this.context, {
1509
- timestamp: (_a = this.options) == null ? void 0 : _a.timestamp,
1510
- logLevels: _LoggerInstance.logLevels
1511
- });
1512
- return this.localInstanceRef;
1513
1636
  }
1514
- };
1515
- _init2 = __decoratorStart(null);
1516
- _LoggerInstance = __decorateElement(_init2, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
1517
- __runInitializers(_init2, 1, _LoggerInstance);
1518
- var LoggerInstance = _LoggerInstance;
1519
-
1520
- // packages/core/src/logger/logger.factory.mts
1521
- var LoggerInjectionToken = "LoggerInjectionToken";
1522
- var LoggerOptions = z2.object({
1523
- context: z2.string().optional(),
1524
- options: z2.object({
1525
- timestamp: z2.boolean().optional()
1526
- }).optional()
1527
- }).optional();
1528
- var Logger = InjectionToken.create(LoggerInjectionToken, LoggerOptions);
1529
- var _LoggerFactory_decorators, _init3;
1530
- _LoggerFactory_decorators = [Injectable({
1531
- type: "Factory" /* Factory */,
1532
- token: Logger
1533
- })];
1534
- var LoggerFactory = class {
1535
- create(ctx, args) {
1536
- return new LoggerInstance(args == null ? void 0 : args.context, args == null ? void 0 : args.options);
1637
+ getAllModules() {
1638
+ return this.modulesMetadata;
1639
+ }
1640
+ dispose() {
1641
+ this.modulesMetadata.clear();
1642
+ this.loadedModules.clear();
1643
+ this.initialized = false;
1537
1644
  }
1538
1645
  };
1539
1646
  _init3 = __decoratorStart(null);
1540
- LoggerFactory = __decorateElement(_init3, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
1541
- __runInitializers(_init3, 1, LoggerFactory);
1647
+ _ModuleLoaderService = __decorateElement(_init3, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
1648
+ __runInitializers(_init3, 1, _ModuleLoaderService);
1649
+ var ModuleLoaderService = _ModuleLoaderService;
1542
1650
 
1543
- // packages/core/src/logger/pino-wrapper.mts
1544
- var PinoWrapper = class _PinoWrapper {
1545
- constructor(logger) {
1546
- this.logger = logger;
1651
+ // packages/core/src/tokens/execution-context.token.mts
1652
+ var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
1653
+ var ExecutionContextToken = InjectionToken.create(
1654
+ ExecutionContextInjectionToken
1655
+ );
1656
+
1657
+ // packages/core/src/tokens/reply.token.mts
1658
+ var ReplyInjectionToken = "ReplyInjectionToken";
1659
+ var Reply = InjectionToken.create(ReplyInjectionToken);
1660
+
1661
+ // packages/core/src/tokens/request.token.mts
1662
+ var RequestInjectionToken = "RequestInjectionToken";
1663
+ var Request = InjectionToken.create(
1664
+ RequestInjectionToken
1665
+ );
1666
+
1667
+ // packages/core/src/logger/console-logger.service.mts
1668
+ var DEFAULT_DEPTH = 5;
1669
+ var DEFAULT_LOG_LEVELS = [
1670
+ "log",
1671
+ "error",
1672
+ "warn",
1673
+ "debug",
1674
+ "verbose",
1675
+ "fatal"
1676
+ ];
1677
+ var dateTimeFormatter = new Intl.DateTimeFormat(void 0, {
1678
+ year: "numeric",
1679
+ hour: "numeric",
1680
+ minute: "numeric",
1681
+ second: "numeric",
1682
+ day: "2-digit",
1683
+ month: "2-digit"
1684
+ });
1685
+ var _ConsoleLogger_decorators, _init4;
1686
+ _ConsoleLogger_decorators = [Injectable()];
1687
+ var _ConsoleLogger = class _ConsoleLogger {
1688
+ /**
1689
+ * The options of the logger.
1690
+ */
1691
+ options;
1692
+ /**
1693
+ * The context of the logger (can be set manually or automatically inferred).
1694
+ */
1695
+ context;
1696
+ /**
1697
+ * Request ID (if enabled).
1698
+ */
1699
+ requestId = null;
1700
+ /**
1701
+ * The original context of the logger (set in the constructor).
1702
+ */
1703
+ originalContext;
1704
+ /**
1705
+ * The options used for the "inspect" method.
1706
+ */
1707
+ inspectOptions;
1708
+ /**
1709
+ * The last timestamp at which the log message was printed.
1710
+ */
1711
+ static lastTimestampAt;
1712
+ constructor(contextOrOptions, options) {
1713
+ let [context, opts] = isString(contextOrOptions) ? [contextOrOptions, options] : options ? [void 0, options] : [contextOrOptions == null ? void 0 : contextOrOptions.context, contextOrOptions];
1714
+ opts = opts ?? {};
1715
+ opts.logLevels ??= DEFAULT_LOG_LEVELS;
1716
+ opts.colors ??= opts.colors ?? (opts.json ? false : true);
1717
+ opts.prefix ??= "Navios";
1718
+ this.options = opts;
1719
+ this.inspectOptions = this.getInspectOptions();
1720
+ if (context) {
1721
+ this.context = context;
1722
+ this.originalContext = context;
1723
+ }
1724
+ if (opts == null ? void 0 : opts.requestId) {
1725
+ const locator = getServiceLocator();
1726
+ locator.getEventBus().on(locator.getInstanceIdentifier(Request, void 0), "create", () => {
1727
+ const request = locator.getSyncInstance(Request, void 0);
1728
+ this.requestId = (request == null ? void 0 : request.id) ?? null;
1729
+ });
1730
+ locator.getEventBus().on(
1731
+ locator.getInstanceIdentifier(Request, void 0),
1732
+ "destroy",
1733
+ () => {
1734
+ this.requestId = null;
1735
+ }
1736
+ );
1737
+ }
1547
1738
  }
1548
- fatal(message, ...optionalParams) {
1549
- if (this.logger.fatal === void 0) {
1550
- return this.error(message, ...optionalParams);
1739
+ log(message, ...optionalParams) {
1740
+ if (!this.isLevelEnabled("log")) {
1741
+ return;
1551
1742
  }
1552
- this.logger.fatal(message, ...optionalParams);
1743
+ const { messages, context } = this.getContextAndMessagesToPrint([
1744
+ message,
1745
+ ...optionalParams
1746
+ ]);
1747
+ this.printMessages(messages, context, "log");
1553
1748
  }
1554
1749
  error(message, ...optionalParams) {
1555
- this.logger.error(message, ...optionalParams);
1750
+ if (!this.isLevelEnabled("error")) {
1751
+ return;
1752
+ }
1753
+ const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([message, ...optionalParams]);
1754
+ this.printMessages(messages, context, "error", "stderr", stack);
1755
+ this.printStackTrace(stack);
1556
1756
  }
1557
1757
  warn(message, ...optionalParams) {
1558
- this.logger.warn(message, ...optionalParams);
1559
- }
1560
- info() {
1758
+ if (!this.isLevelEnabled("warn")) {
1759
+ return;
1760
+ }
1761
+ const { messages, context } = this.getContextAndMessagesToPrint([
1762
+ message,
1763
+ ...optionalParams
1764
+ ]);
1765
+ this.printMessages(messages, context, "warn");
1561
1766
  }
1562
1767
  debug(message, ...optionalParams) {
1563
- var _a, _b;
1564
- (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1565
- }
1566
- trace(message, ...optionalParams) {
1567
- var _a, _b;
1568
- (_b = (_a = this.logger).verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
1569
- }
1570
- silent() {
1571
- }
1572
- child(options) {
1573
- const keys = Object.keys(options);
1574
- let newContext = this.logger["context"] ?? "";
1575
- if (keys.length > 1) {
1576
- newContext = `${this.logger["context"] ?? ""}:${JSON.stringify(options)}`;
1768
+ if (!this.isLevelEnabled("debug")) {
1769
+ return;
1577
1770
  }
1578
- return new _PinoWrapper(
1579
- // @ts-expect-error We don't need to support this in the current version
1580
- new LoggerInstance(newContext, this.logger["options"])
1581
- );
1771
+ const { messages, context } = this.getContextAndMessagesToPrint([
1772
+ message,
1773
+ ...optionalParams
1774
+ ]);
1775
+ this.printMessages(messages, context, "debug");
1582
1776
  }
1583
- get level() {
1584
- if ("level" in this.logger && this.logger.level) {
1585
- return this.logger.level;
1586
- }
1587
- const levels = LoggerInstance["logLevels"];
1588
- if (levels) {
1589
- return levels.find((level) => level !== "verbose");
1777
+ verbose(message, ...optionalParams) {
1778
+ if (!this.isLevelEnabled("verbose")) {
1779
+ return;
1590
1780
  }
1591
- return "warn";
1592
- }
1593
- };
1594
-
1595
- // packages/core/src/config/config.service.mts
1596
- import { NaviosException as NaviosException3 } from "@navios/common";
1597
- var ConfigServiceInstance = class {
1598
- constructor(config = {}, logger) {
1599
- this.config = config;
1600
- this.logger = logger;
1781
+ const { messages, context } = this.getContextAndMessagesToPrint([
1782
+ message,
1783
+ ...optionalParams
1784
+ ]);
1785
+ this.printMessages(messages, context, "verbose");
1601
1786
  }
1602
- getConfig() {
1603
- return this.config;
1787
+ fatal(message, ...optionalParams) {
1788
+ if (!this.isLevelEnabled("fatal")) {
1789
+ return;
1790
+ }
1791
+ const { messages, context } = this.getContextAndMessagesToPrint([
1792
+ message,
1793
+ ...optionalParams
1794
+ ]);
1795
+ this.printMessages(messages, context, "fatal");
1604
1796
  }
1605
- get(key) {
1606
- var _a, _b;
1607
- try {
1608
- const parts = String(key).split(".");
1609
- let value = this.config;
1610
- for (const part of parts) {
1611
- if (value === null || value === void 0 || typeof value !== "object") {
1612
- return null;
1613
- }
1614
- value = value[part];
1615
- }
1616
- return value ?? null;
1617
- } catch (error) {
1618
- (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(
1619
- _a,
1620
- `Failed to get config value for key ${String(key)}`,
1621
- error
1622
- );
1623
- return null;
1797
+ /**
1798
+ * Set log levels
1799
+ * @param levels log levels
1800
+ */
1801
+ setLogLevels(levels) {
1802
+ if (!this.options) {
1803
+ this.options = {};
1624
1804
  }
1805
+ this.options.logLevels = levels;
1625
1806
  }
1626
- getOrDefault(key, defaultValue) {
1627
- const value = this.get(key);
1628
- return value !== null ? value : defaultValue;
1807
+ /**
1808
+ * Set logger context
1809
+ * @param context context
1810
+ */
1811
+ setContext(context) {
1812
+ this.context = context;
1629
1813
  }
1630
- getOrThrow(key, errorMessage) {
1631
- const value = this.get(key);
1632
- if (value === null) {
1633
- const message = errorMessage || `Configuration value for key "${String(key)}" is not defined`;
1634
- this.logger.error(message);
1635
- throw new NaviosException3(message);
1636
- }
1637
- return value;
1814
+ /**
1815
+ * Resets the logger context to the value that was passed in the constructor.
1816
+ */
1817
+ resetContext() {
1818
+ this.context = this.originalContext;
1638
1819
  }
1639
- };
1640
-
1641
- // packages/core/src/config/config.provider.mts
1642
- var ConfigProviderOptions = z3.object({
1643
- load: z3.function()
1644
- });
1645
- var ConfigProvider = InjectionToken.create(ConfigServiceInstance, ConfigProviderOptions);
1646
- var _ConfigProviderFactory_decorators, _init4;
1647
- _ConfigProviderFactory_decorators = [Injectable({
1648
- token: ConfigProvider,
1649
- type: "Factory" /* Factory */
1650
- })];
1651
- var ConfigProviderFactory = class {
1652
- logger = syncInject(Logger, {
1653
- context: "ConfigService"
1654
- });
1655
- async create(ctx, args) {
1656
- const { load } = args;
1657
- const logger = this.logger;
1658
- try {
1659
- const config = await load();
1660
- return new ConfigServiceInstance(config, logger);
1661
- } catch (error) {
1662
- logger.error("Error loading config", error);
1663
- throw error;
1664
- }
1820
+ isLevelEnabled(level) {
1821
+ var _a;
1822
+ const logLevels = (_a = this.options) == null ? void 0 : _a.logLevels;
1823
+ return isLogLevelEnabled(level, logLevels);
1665
1824
  }
1666
- };
1667
- _init4 = __decoratorStart(null);
1668
- ConfigProviderFactory = __decorateElement(_init4, 0, "ConfigProviderFactory", _ConfigProviderFactory_decorators, ConfigProviderFactory);
1669
- __runInitializers(_init4, 1, ConfigProviderFactory);
1670
- function provideConfig(options) {
1671
- return InjectionToken.bound(ConfigProvider, options);
1672
- }
1673
-
1674
- // packages/core/src/metadata/endpoint.metadata.mts
1675
- var EndpointMetadataKey = Symbol("EndpointMetadataKey");
1676
- var EndpointType = /* @__PURE__ */ ((EndpointType2) => {
1677
- EndpointType2["Unknown"] = "unknown";
1678
- EndpointType2["Endpoint"] = "endpoint";
1679
- EndpointType2["Stream"] = "stream";
1680
- EndpointType2["Multipart"] = "multipart";
1681
- EndpointType2["Handler"] = "handler";
1682
- return EndpointType2;
1683
- })(EndpointType || {});
1684
- function getAllEndpointMetadata(context) {
1685
- if (context.metadata) {
1686
- const metadata = context.metadata[EndpointMetadataKey];
1687
- if (metadata) {
1688
- return metadata;
1689
- } else {
1690
- context.metadata[EndpointMetadataKey] = /* @__PURE__ */ new Set();
1691
- return context.metadata[EndpointMetadataKey];
1692
- }
1825
+ getTimestamp() {
1826
+ return dateTimeFormatter.format(Date.now());
1693
1827
  }
1694
- throw new Error("[Navios] Wrong environment.");
1695
- }
1696
- function getEndpointMetadata(target, context) {
1697
- if (context.metadata) {
1698
- const metadata = getAllEndpointMetadata(context);
1699
- if (metadata) {
1700
- const endpointMetadata = Array.from(metadata).find(
1701
- (item) => item.classMethod === target.name
1702
- );
1703
- if (endpointMetadata) {
1704
- return endpointMetadata;
1705
- } else {
1706
- const newMetadata = {
1707
- classMethod: target.name,
1708
- url: "",
1709
- successStatusCode: 200,
1710
- headers: {},
1711
- type: "unknown" /* Unknown */,
1712
- httpMethod: "GET",
1713
- config: null,
1714
- guards: /* @__PURE__ */ new Set(),
1715
- customAttributes: /* @__PURE__ */ new Map()
1716
- };
1717
- metadata.add(newMetadata);
1718
- return newMetadata;
1828
+ printMessages(messages, context = "", logLevel = "log", writeStreamType, errorStack) {
1829
+ messages.forEach((message) => {
1830
+ if (this.options.json) {
1831
+ this.printAsJson(message, {
1832
+ context,
1833
+ logLevel,
1834
+ writeStreamType,
1835
+ errorStack
1836
+ });
1837
+ return;
1719
1838
  }
1720
- }
1839
+ const pidMessage = this.formatPid(process.pid);
1840
+ const contextMessage = this.formatContext(context);
1841
+ const timestampDiff = this.updateAndGetTimestampDiff();
1842
+ const formattedLogLevel = logLevel.toUpperCase().padStart(7, " ");
1843
+ const formattedMessage = this.formatMessage(
1844
+ logLevel,
1845
+ message,
1846
+ pidMessage,
1847
+ formattedLogLevel,
1848
+ contextMessage,
1849
+ timestampDiff
1850
+ );
1851
+ process[writeStreamType ?? "stdout"].write(formattedMessage);
1852
+ });
1721
1853
  }
1722
- throw new Error("[Navios] Wrong environment.");
1723
- }
1724
-
1725
- // packages/core/src/metadata/controller.metadata.mts
1726
- var ControllerMetadataKey = Symbol("ControllerMetadataKey");
1727
- function getControllerMetadata(target, context) {
1728
- if (context.metadata) {
1729
- const metadata = context.metadata[ControllerMetadataKey];
1730
- if (metadata) {
1731
- return metadata;
1732
- } else {
1733
- const endpointsMetadata = getAllEndpointMetadata(context);
1734
- const newMetadata = {
1735
- endpoints: endpointsMetadata,
1736
- guards: /* @__PURE__ */ new Set(),
1737
- customAttributes: /* @__PURE__ */ new Map()
1738
- };
1739
- context.metadata[ControllerMetadataKey] = newMetadata;
1740
- target[ControllerMetadataKey] = newMetadata;
1741
- return newMetadata;
1854
+ printAsJson(message, options) {
1855
+ const logObject = {
1856
+ level: options.logLevel,
1857
+ pid: process.pid,
1858
+ timestamp: Date.now(),
1859
+ message
1860
+ };
1861
+ if (options.context) {
1862
+ logObject.context = options.context;
1863
+ }
1864
+ if (options.errorStack) {
1865
+ logObject.stack = options.errorStack;
1866
+ }
1867
+ if (this.options.requestId && this.requestId) {
1868
+ logObject.requestId = this.requestId;
1742
1869
  }
1870
+ const formattedMessage = !this.options.colors && this.inspectOptions.compact === true ? JSON.stringify(logObject, this.stringifyReplacer) : inspect(logObject, this.inspectOptions);
1871
+ process[options.writeStreamType ?? "stdout"].write(`${formattedMessage}
1872
+ `);
1743
1873
  }
1744
- throw new Error("[Navios] Wrong environment.");
1745
- }
1746
- function extractControllerMetadata(target) {
1747
- const metadata = target[ControllerMetadataKey];
1748
- if (!metadata) {
1749
- throw new Error(
1750
- "[Navios] Controller metadata not found. Make sure to use @Controller decorator."
1751
- );
1874
+ formatPid(pid) {
1875
+ return `[${this.options.prefix}] ${pid} - `;
1752
1876
  }
1753
- return metadata;
1754
- }
1755
- function hasControllerMetadata(target) {
1756
- const metadata = target[ControllerMetadataKey];
1757
- return !!metadata;
1758
- }
1759
-
1760
- // packages/core/src/metadata/module.metadata.mts
1761
- var ModuleMetadataKey = Symbol("ControllerMetadataKey");
1762
- function getModuleMetadata(target, context) {
1763
- if (context.metadata) {
1764
- const metadata = context.metadata[ModuleMetadataKey];
1765
- if (metadata) {
1766
- return metadata;
1767
- } else {
1768
- const newMetadata = {
1769
- controllers: /* @__PURE__ */ new Set(),
1770
- imports: /* @__PURE__ */ new Set(),
1771
- guards: /* @__PURE__ */ new Set(),
1772
- customAttributes: /* @__PURE__ */ new Map()
1773
- };
1774
- context.metadata[ModuleMetadataKey] = newMetadata;
1775
- target[ModuleMetadataKey] = newMetadata;
1776
- return newMetadata;
1877
+ formatContext(context) {
1878
+ if (!context) {
1879
+ return "";
1777
1880
  }
1881
+ context = `[${context}] `;
1882
+ return this.options.colors ? yellow(context) : context;
1778
1883
  }
1779
- throw new Error("[Navios] Wrong environment.");
1780
- }
1781
- function extractModuleMetadata(target) {
1782
- const metadata = target[ModuleMetadataKey];
1783
- if (!metadata) {
1784
- throw new Error(
1785
- `[Navios] Module metadata not found for ${target.name}. Make sure to use @Module decorator.`
1786
- );
1884
+ formatMessage(logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
1885
+ const output = this.stringifyMessage(message, logLevel);
1886
+ pidMessage = this.colorize(pidMessage, logLevel);
1887
+ formattedLogLevel = this.colorize(formattedLogLevel, logLevel);
1888
+ return `${pidMessage}${this.getRequestId()}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}
1889
+ `;
1787
1890
  }
1788
- return metadata;
1789
- }
1790
- function hasModuleMetadata(target) {
1791
- return !!target[ModuleMetadataKey];
1792
- }
1793
-
1794
- // packages/core/src/decorators/controller.decorator.mts
1795
- function Controller({ guards } = {}) {
1796
- return function(target, context) {
1797
- if (context.kind !== "class") {
1798
- throw new Error(
1799
- "[Navios] @Controller decorator can only be used on classes."
1800
- );
1891
+ getRequestId() {
1892
+ if (this.options.requestId && this.requestId) {
1893
+ return `(${this.colorize(this.requestId, "log")}) `;
1801
1894
  }
1802
- const token = InjectionToken.create(target);
1803
- if (context.metadata) {
1804
- const controllerMetadata = getControllerMetadata(target, context);
1805
- if (guards) {
1806
- for (const guard of Array.from(guards).reverse()) {
1807
- controllerMetadata.guards.add(guard);
1808
- }
1895
+ return "";
1896
+ }
1897
+ stringifyMessage(message, logLevel) {
1898
+ if (isFunction(message)) {
1899
+ const messageAsStr = Function.prototype.toString.call(message);
1900
+ const isClass = messageAsStr.startsWith("class ");
1901
+ if (isClass) {
1902
+ return this.stringifyMessage(message.name, logLevel);
1809
1903
  }
1904
+ return this.stringifyMessage(message(), logLevel);
1810
1905
  }
1811
- return Injectable({
1812
- token,
1813
- type: "Class" /* Class */,
1814
- scope: "Instance" /* Instance */
1815
- })(target, context);
1816
- };
1817
- }
1818
-
1819
- // packages/core/src/decorators/endpoint.decorator.mts
1820
- import "zod";
1821
- function Endpoint(endpoint) {
1822
- return (target, context) => {
1823
- if (typeof target !== "function") {
1824
- throw new Error(
1825
- "[Navios] Endpoint decorator can only be used on functions."
1826
- );
1906
+ if (typeof message === "string") {
1907
+ return this.colorize(message, logLevel);
1827
1908
  }
1828
- if (context.kind !== "method") {
1829
- throw new Error(
1830
- "[Navios] Endpoint decorator can only be used on methods."
1831
- );
1909
+ const outputText = inspect(message, this.inspectOptions);
1910
+ if (isPlainObject(message)) {
1911
+ return `Object(${Object.keys(message).length}) ${outputText}`;
1832
1912
  }
1833
- const config = endpoint.config;
1834
- if (context.metadata) {
1835
- let endpointMetadata = getEndpointMetadata(target, context);
1836
- if (endpointMetadata.config && endpointMetadata.config.url) {
1837
- throw new Error(
1838
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
1839
- );
1840
- }
1841
- endpointMetadata.config = config;
1842
- endpointMetadata.type = "endpoint" /* Endpoint */;
1843
- endpointMetadata.classMethod = target.name;
1844
- endpointMetadata.httpMethod = config.method;
1845
- endpointMetadata.url = config.url;
1913
+ if (Array.isArray(message)) {
1914
+ return `Array(${message.length}) ${outputText}`;
1846
1915
  }
1847
- return target;
1848
- };
1849
- }
1850
-
1851
- // packages/core/src/decorators/header.decorator.mts
1852
- function Header(name2, value) {
1853
- return (target, context) => {
1854
- if (context.kind !== "method") {
1855
- throw new Error("[Navios] Header decorator can only be used on methods.");
1916
+ return outputText;
1917
+ }
1918
+ colorize(message, logLevel) {
1919
+ if (!this.options.colors || this.options.json) {
1920
+ return message;
1856
1921
  }
1857
- const metadata = getEndpointMetadata(target, context);
1858
- if (metadata.type === "stream" /* Stream */) {
1859
- throw new Error(
1860
- "[Navios] HttpCode decorator cannot be used on stream endpoints."
1861
- );
1922
+ const color = this.getColorByLogLevel(logLevel);
1923
+ return color(message);
1924
+ }
1925
+ printStackTrace(stack) {
1926
+ if (!stack || this.options.json) {
1927
+ return;
1862
1928
  }
1863
- metadata.headers[name2] = value;
1864
- return target;
1865
- };
1866
- }
1867
-
1868
- // packages/core/src/decorators/http-code.decorator.mts
1869
- function HttpCode(code) {
1870
- return (target, context) => {
1871
- if (context.kind !== "method") {
1872
- throw new Error(
1873
- "[Navios] HttpCode decorator can only be used on methods."
1874
- );
1929
+ process.stderr.write(`${stack}
1930
+ `);
1931
+ }
1932
+ updateAndGetTimestampDiff() {
1933
+ var _a;
1934
+ const includeTimestamp = _ConsoleLogger.lastTimestampAt && ((_a = this.options) == null ? void 0 : _a.timestamp);
1935
+ const result = includeTimestamp ? this.formatTimestampDiff(Date.now() - _ConsoleLogger.lastTimestampAt) : "";
1936
+ _ConsoleLogger.lastTimestampAt = Date.now();
1937
+ return result;
1938
+ }
1939
+ formatTimestampDiff(timestampDiff) {
1940
+ const formattedDiff = ` +${timestampDiff}ms`;
1941
+ return this.options.colors ? yellow(formattedDiff) : formattedDiff;
1942
+ }
1943
+ getInspectOptions() {
1944
+ let breakLength = this.options.breakLength;
1945
+ if (typeof breakLength === "undefined") {
1946
+ breakLength = this.options.colors ? this.options.compact ? Infinity : void 0 : this.options.compact === false ? void 0 : Infinity;
1875
1947
  }
1876
- const metadata = getEndpointMetadata(target, context);
1877
- if (metadata.type === "stream" /* Stream */) {
1878
- throw new Error(
1879
- "[Navios] HttpCode decorator cannot be used on stream endpoints."
1880
- );
1948
+ const inspectOptions = {
1949
+ depth: this.options.depth ?? DEFAULT_DEPTH,
1950
+ sorted: this.options.sorted,
1951
+ showHidden: this.options.showHidden,
1952
+ compact: this.options.compact ?? (this.options.json ? true : false),
1953
+ colors: this.options.colors,
1954
+ breakLength
1955
+ };
1956
+ if (this.options.maxArrayLength) {
1957
+ inspectOptions.maxArrayLength = this.options.maxArrayLength;
1881
1958
  }
1882
- metadata.successStatusCode = code;
1883
- return target;
1884
- };
1885
- }
1886
-
1887
- // packages/core/src/decorators/module.decorator.mts
1888
- function Module(metadata) {
1889
- return (target, context) => {
1890
- if (context.kind !== "class") {
1891
- throw new Error("[Navios] @Module decorator can only be used on classes.");
1959
+ if (this.options.maxStringLength) {
1960
+ inspectOptions.maxStringLength = this.options.maxStringLength;
1961
+ }
1962
+ return inspectOptions;
1963
+ }
1964
+ stringifyReplacer(key, value) {
1965
+ if (typeof value === "bigint") {
1966
+ return value.toString();
1892
1967
  }
1893
- const token = InjectionToken.create(target);
1894
- const moduleMetadata = getModuleMetadata(target, context);
1895
- if (metadata.controllers) {
1896
- for (const controller of metadata.controllers) {
1897
- moduleMetadata.controllers.add(controller);
1898
- }
1968
+ if (typeof value === "symbol") {
1969
+ return value.toString();
1899
1970
  }
1900
- if (metadata.imports) {
1901
- for (const importedModule of metadata.imports) {
1902
- moduleMetadata.imports.add(importedModule);
1903
- }
1971
+ if (value instanceof Map || value instanceof Set || value instanceof Error) {
1972
+ return `${inspect(value, this.inspectOptions)}`;
1904
1973
  }
1905
- if (metadata.guards) {
1906
- for (const guard of Array.from(metadata.guards).reverse()) {
1907
- moduleMetadata.guards.add(guard);
1908
- }
1974
+ return value;
1975
+ }
1976
+ getContextAndMessagesToPrint(args) {
1977
+ if ((args == null ? void 0 : args.length) <= 1) {
1978
+ return { messages: args, context: this.context };
1909
1979
  }
1910
- return Injectable({
1911
- token,
1912
- type: "Class" /* Class */,
1913
- scope: "Singleton" /* Singleton */
1914
- })(target, context);
1915
- };
1916
- }
1917
-
1918
- // packages/core/src/decorators/multipart.decorator.mts
1919
- import "zod";
1920
- function Multipart(endpoint) {
1921
- return (target, context) => {
1922
- if (typeof target !== "function") {
1923
- throw new Error(
1924
- "[Navios] Endpoint decorator can only be used on functions."
1925
- );
1980
+ const lastElement = args[args.length - 1];
1981
+ const isContext = isString(lastElement);
1982
+ if (!isContext) {
1983
+ return { messages: args, context: this.context };
1926
1984
  }
1927
- if (context.kind !== "method") {
1928
- throw new Error(
1929
- "[Navios] Endpoint decorator can only be used on methods."
1930
- );
1985
+ return {
1986
+ context: lastElement,
1987
+ messages: args.slice(0, args.length - 1)
1988
+ };
1989
+ }
1990
+ getContextAndStackAndMessagesToPrint(args) {
1991
+ if (args.length === 2) {
1992
+ return this.isStackFormat(args[1]) ? {
1993
+ messages: [args[0]],
1994
+ stack: args[1],
1995
+ context: this.context
1996
+ } : {
1997
+ messages: [args[0]],
1998
+ context: args[1]
1999
+ };
1931
2000
  }
1932
- const config = endpoint.config;
1933
- if (context.metadata) {
1934
- let endpointMetadata = getEndpointMetadata(target, context);
1935
- if (endpointMetadata.config && endpointMetadata.config.url) {
1936
- throw new Error(
1937
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
1938
- );
1939
- }
1940
- endpointMetadata.config = config;
1941
- endpointMetadata.type = "multipart" /* Multipart */;
1942
- endpointMetadata.classMethod = target.name;
1943
- endpointMetadata.httpMethod = config.method;
1944
- endpointMetadata.url = config.url;
2001
+ const { messages, context } = this.getContextAndMessagesToPrint(args);
2002
+ if ((messages == null ? void 0 : messages.length) <= 1) {
2003
+ return { messages, context };
1945
2004
  }
1946
- return target;
1947
- };
1948
- }
1949
-
1950
- // packages/core/src/decorators/stream.decorator.mts
1951
- function Stream(endpoint) {
1952
- return (target, context) => {
1953
- if (typeof target !== "function") {
1954
- throw new Error(
1955
- "[Navios] Endpoint decorator can only be used on functions."
1956
- );
2005
+ const lastElement = messages[messages.length - 1];
2006
+ const isStack = isString(lastElement);
2007
+ if (!isStack && !isUndefined(lastElement)) {
2008
+ return { messages, context };
1957
2009
  }
1958
- if (context.kind !== "method") {
1959
- throw new Error(
1960
- "[Navios] Endpoint decorator can only be used on methods."
1961
- );
2010
+ return {
2011
+ stack: lastElement,
2012
+ messages: messages.slice(0, messages.length - 1),
2013
+ context
2014
+ };
2015
+ }
2016
+ isStackFormat(stack) {
2017
+ if (!isString(stack) && !isUndefined(stack)) {
2018
+ return false;
1962
2019
  }
1963
- const config = endpoint.config;
1964
- if (context.metadata) {
1965
- let endpointMetadata = getEndpointMetadata(target, context);
1966
- if (endpointMetadata.config && endpointMetadata.config.url) {
1967
- throw new Error(
1968
- `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
1969
- );
1970
- }
1971
- endpointMetadata.config = config;
1972
- endpointMetadata.type = "stream" /* Stream */;
1973
- endpointMetadata.classMethod = target.name;
1974
- endpointMetadata.httpMethod = config.method;
1975
- endpointMetadata.url = config.url;
2020
+ return /^(.)+\n\s+at .+:\d+:\d+/.test(stack);
2021
+ }
2022
+ getColorByLogLevel(level) {
2023
+ switch (level) {
2024
+ case "debug":
2025
+ return clc.magentaBright;
2026
+ case "warn":
2027
+ return clc.yellow;
2028
+ case "error":
2029
+ return clc.red;
2030
+ case "verbose":
2031
+ return clc.cyanBright;
2032
+ case "fatal":
2033
+ return clc.bold;
2034
+ default:
2035
+ return clc.green;
1976
2036
  }
1977
- return target;
1978
- };
1979
- }
2037
+ }
2038
+ };
2039
+ _init4 = __decoratorStart(null);
2040
+ _ConsoleLogger = __decorateElement(_init4, 0, "ConsoleLogger", _ConsoleLogger_decorators, _ConsoleLogger);
2041
+ __runInitializers(_init4, 1, _ConsoleLogger);
2042
+ var ConsoleLogger = _ConsoleLogger;
1980
2043
 
1981
- // packages/core/src/decorators/use-guards.decorator.mts
1982
- function UseGuards(...guards) {
1983
- return function(target, context) {
1984
- if (context.kind === "class") {
1985
- const controllerMetadata = getControllerMetadata(
1986
- target,
1987
- context
1988
- );
1989
- for (const guard of guards.reverse()) {
1990
- controllerMetadata.guards.add(guard);
1991
- }
1992
- } else if (context.kind === "method") {
1993
- const endpointMetadata = getEndpointMetadata(target, context);
1994
- for (const guard of guards.reverse()) {
1995
- endpointMetadata.guards.add(guard);
2044
+ // packages/core/src/logger/logger.factory.mts
2045
+ import { z as z2 } from "zod";
2046
+
2047
+ // packages/core/src/logger/logger.service.mts
2048
+ var DEFAULT_LOGGER = new ConsoleLogger();
2049
+ var dateTimeFormatter2 = new Intl.DateTimeFormat(void 0, {
2050
+ year: "numeric",
2051
+ hour: "numeric",
2052
+ minute: "numeric",
2053
+ second: "numeric",
2054
+ day: "2-digit",
2055
+ month: "2-digit"
2056
+ });
2057
+ var _LoggerInstance_decorators, _init5;
2058
+ _LoggerInstance_decorators = [Injectable()];
2059
+ var _LoggerInstance = class _LoggerInstance {
2060
+ constructor(context, options = {}) {
2061
+ this.context = context;
2062
+ this.options = options;
2063
+ }
2064
+ static staticInstanceRef = DEFAULT_LOGGER;
2065
+ static logLevels;
2066
+ localInstanceRef;
2067
+ get localInstance() {
2068
+ if (_LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {
2069
+ return this.registerLocalInstanceRef();
2070
+ } else if (_LoggerInstance.staticInstanceRef instanceof _LoggerInstance) {
2071
+ const prototype = Object.getPrototypeOf(_LoggerInstance.staticInstanceRef);
2072
+ if (prototype.constructor === _LoggerInstance) {
2073
+ return this.registerLocalInstanceRef();
1996
2074
  }
2075
+ }
2076
+ return _LoggerInstance.staticInstanceRef;
2077
+ }
2078
+ error(message, ...optionalParams) {
2079
+ var _a;
2080
+ optionalParams = this.context ? (optionalParams.length ? optionalParams : [void 0]).concat(
2081
+ this.context
2082
+ ) : optionalParams;
2083
+ (_a = this.localInstance) == null ? void 0 : _a.error(message, ...optionalParams);
2084
+ }
2085
+ log(message, ...optionalParams) {
2086
+ var _a;
2087
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2088
+ (_a = this.localInstance) == null ? void 0 : _a.log(message, ...optionalParams);
2089
+ }
2090
+ warn(message, ...optionalParams) {
2091
+ var _a;
2092
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2093
+ (_a = this.localInstance) == null ? void 0 : _a.warn(message, ...optionalParams);
2094
+ }
2095
+ debug(message, ...optionalParams) {
2096
+ var _a, _b;
2097
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2098
+ (_b = (_a = this.localInstance) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2099
+ }
2100
+ verbose(message, ...optionalParams) {
2101
+ var _a, _b;
2102
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2103
+ (_b = (_a = this.localInstance) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2104
+ }
2105
+ fatal(message, ...optionalParams) {
2106
+ var _a, _b;
2107
+ optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams;
2108
+ (_b = (_a = this.localInstance) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2109
+ }
2110
+ static error(message, ...optionalParams) {
2111
+ var _a;
2112
+ (_a = this.staticInstanceRef) == null ? void 0 : _a.error(message, ...optionalParams);
2113
+ }
2114
+ static log(message, ...optionalParams) {
2115
+ var _a;
2116
+ (_a = this.staticInstanceRef) == null ? void 0 : _a.log(message, ...optionalParams);
2117
+ }
2118
+ static warn(message, ...optionalParams) {
2119
+ var _a;
2120
+ (_a = this.staticInstanceRef) == null ? void 0 : _a.warn(message, ...optionalParams);
2121
+ }
2122
+ static debug(message, ...optionalParams) {
2123
+ var _a, _b;
2124
+ (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2125
+ }
2126
+ static verbose(message, ...optionalParams) {
2127
+ var _a, _b;
2128
+ (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2129
+ }
2130
+ static fatal(message, ...optionalParams) {
2131
+ var _a, _b;
2132
+ (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.fatal) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2133
+ }
2134
+ static getTimestamp() {
2135
+ return dateTimeFormatter2.format(Date.now());
2136
+ }
2137
+ static overrideLogger(logger) {
2138
+ var _a, _b;
2139
+ if (Array.isArray(logger)) {
2140
+ _LoggerInstance.logLevels = logger;
2141
+ return (_b = (_a = this.staticInstanceRef) == null ? void 0 : _a.setLogLevels) == null ? void 0 : _b.call(_a, logger);
2142
+ }
2143
+ if (isObject(logger)) {
2144
+ this.staticInstanceRef = logger;
1997
2145
  } else {
1998
- throw new Error(
1999
- "[Navios] @UseGuards decorator can only be used on classes or methods."
2000
- );
2146
+ this.staticInstanceRef = void 0;
2001
2147
  }
2002
- return target;
2003
- };
2004
- }
2005
-
2006
- // packages/core/src/exceptions/http.exception.mts
2007
- var HttpException = class {
2008
- constructor(statusCode, response, error) {
2009
- this.statusCode = statusCode;
2010
- this.response = response;
2011
- this.error = error;
2012
2148
  }
2013
- };
2014
-
2015
- // packages/core/src/exceptions/bad-request.exception.mts
2016
- var BadRequestException = class extends HttpException {
2017
- constructor(message) {
2018
- super(400, message);
2149
+ static isLevelEnabled(level) {
2150
+ const logLevels = _LoggerInstance.logLevels;
2151
+ return isLogLevelEnabled(level, logLevels);
2019
2152
  }
2020
- };
2021
-
2022
- // packages/core/src/exceptions/forbidden.exception.mts
2023
- var ForbiddenException = class extends HttpException {
2024
- constructor(message) {
2025
- super(403, message);
2153
+ registerLocalInstanceRef() {
2154
+ var _a;
2155
+ if (this.localInstanceRef) {
2156
+ return this.localInstanceRef;
2157
+ }
2158
+ this.localInstanceRef = new ConsoleLogger(this.context, {
2159
+ timestamp: (_a = this.options) == null ? void 0 : _a.timestamp,
2160
+ logLevels: _LoggerInstance.logLevels
2161
+ });
2162
+ return this.localInstanceRef;
2026
2163
  }
2027
2164
  };
2165
+ _init5 = __decoratorStart(null);
2166
+ _LoggerInstance = __decorateElement(_init5, 0, "LoggerInstance", _LoggerInstance_decorators, _LoggerInstance);
2167
+ __runInitializers(_init5, 1, _LoggerInstance);
2168
+ var LoggerInstance = _LoggerInstance;
2028
2169
 
2029
- // packages/core/src/exceptions/internal-server-error.exception.mts
2030
- var InternalServerErrorException = class extends HttpException {
2031
- constructor(message, error) {
2032
- super(500, message, error);
2170
+ // packages/core/src/logger/logger.factory.mts
2171
+ var LoggerInjectionToken = "LoggerInjectionToken";
2172
+ var LoggerOptions = z2.object({
2173
+ context: z2.string().optional(),
2174
+ options: z2.object({
2175
+ timestamp: z2.boolean().optional()
2176
+ }).optional()
2177
+ }).optional();
2178
+ var Logger = InjectionToken.create(LoggerInjectionToken, LoggerOptions);
2179
+ var _LoggerFactory_decorators, _init6;
2180
+ _LoggerFactory_decorators = [Injectable({
2181
+ type: "Factory" /* Factory */,
2182
+ token: Logger
2183
+ })];
2184
+ var LoggerFactory = class {
2185
+ create(ctx, args) {
2186
+ return new LoggerInstance(args == null ? void 0 : args.context, args == null ? void 0 : args.options);
2033
2187
  }
2034
2188
  };
2189
+ _init6 = __decoratorStart(null);
2190
+ LoggerFactory = __decorateElement(_init6, 0, "LoggerFactory", _LoggerFactory_decorators, LoggerFactory);
2191
+ __runInitializers(_init6, 1, LoggerFactory);
2035
2192
 
2036
- // packages/core/src/exceptions/not-found.exception.mts
2037
- var NotFoundException = class extends HttpException {
2038
- constructor(response, error) {
2039
- super(404, response, error);
2040
- this.response = response;
2041
- this.error = error;
2193
+ // packages/core/src/logger/pino-wrapper.mts
2194
+ var PinoWrapper = class _PinoWrapper {
2195
+ constructor(logger) {
2196
+ this.logger = logger;
2042
2197
  }
2043
- };
2044
-
2045
- // packages/core/src/exceptions/unauthorized.exception.mts
2046
- var UnauthorizedException = class extends HttpException {
2047
- constructor(message, error) {
2048
- super(401, message, error);
2198
+ fatal(message, ...optionalParams) {
2199
+ if (this.logger.fatal === void 0) {
2200
+ return this.error(message, ...optionalParams);
2201
+ }
2202
+ this.logger.fatal(message, ...optionalParams);
2049
2203
  }
2050
- };
2051
-
2052
- // packages/core/src/exceptions/conflict.exception.mts
2053
- var ConflictException = class extends HttpException {
2054
- constructor(message, error) {
2055
- super(409, message, error);
2204
+ error(message, ...optionalParams) {
2205
+ this.logger.error(message, ...optionalParams);
2056
2206
  }
2057
- };
2058
-
2059
- // packages/core/src/services/controller-adapter.service.mts
2060
- import { NaviosException as NaviosException4 } from "@navios/common";
2061
- import { ZodArray } from "zod";
2062
-
2063
- // packages/core/src/tokens/application.token.mts
2064
- var ApplicationInjectionToken = "ApplicationInjectionToken";
2065
- var Application = InjectionToken.create(
2066
- ApplicationInjectionToken
2067
- );
2068
-
2069
- // packages/core/src/tokens/execution-context.token.mts
2070
- var ExecutionContextInjectionToken = "ExecutionContextInjectionToken";
2071
- var ExecutionContextToken = InjectionToken.create(
2072
- ExecutionContextInjectionToken
2073
- );
2074
-
2075
- // packages/core/src/tokens/reply.token.mts
2076
- var ReplyInjectionToken = "ReplyInjectionToken";
2077
- var Reply = InjectionToken.create(ReplyInjectionToken);
2078
-
2079
- // packages/core/src/tokens/request.token.mts
2080
- var RequestInjectionToken = "RequestInjectionToken";
2081
- var Request = InjectionToken.create(
2082
- RequestInjectionToken
2083
- );
2084
-
2085
- // packages/core/src/services/execution-context.mts
2086
- var ExecutionContext2 = class {
2087
- constructor(module, controller, handler) {
2088
- this.module = module;
2089
- this.controller = controller;
2090
- this.handler = handler;
2207
+ warn(message, ...optionalParams) {
2208
+ this.logger.warn(message, ...optionalParams);
2091
2209
  }
2092
- request;
2093
- reply;
2094
- getModule() {
2095
- return this.module;
2210
+ info() {
2096
2211
  }
2097
- getController() {
2098
- return this.controller;
2212
+ debug(message, ...optionalParams) {
2213
+ var _a, _b;
2214
+ (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2099
2215
  }
2100
- getHandler() {
2101
- return this.handler;
2216
+ trace(message, ...optionalParams) {
2217
+ var _a, _b;
2218
+ (_b = (_a = this.logger).verbose) == null ? void 0 : _b.call(_a, message, ...optionalParams);
2102
2219
  }
2103
- getRequest() {
2104
- if (!this.request) {
2105
- throw new Error(
2106
- "[Navios] Request is not set. Make sure to set it before using it."
2107
- );
2108
- }
2109
- return this.request;
2220
+ silent() {
2110
2221
  }
2111
- getReply() {
2112
- if (!this.reply) {
2113
- throw new Error(
2114
- "[Navios] Reply is not set. Make sure to set it before using it."
2115
- );
2222
+ child(options) {
2223
+ const keys = Object.keys(options);
2224
+ let newContext = this.logger["context"] ?? "";
2225
+ if (keys.length > 1) {
2226
+ newContext = `${this.logger["context"] ?? ""}:${JSON.stringify(options)}`;
2116
2227
  }
2117
- return this.reply;
2118
- }
2119
- provideRequest(request) {
2120
- this.request = request;
2228
+ return new _PinoWrapper(
2229
+ // @ts-expect-error We don't need to support this in the current version
2230
+ new LoggerInstance(newContext, this.logger["options"])
2231
+ );
2121
2232
  }
2122
- provideReply(reply) {
2123
- this.reply = reply;
2233
+ get level() {
2234
+ if ("level" in this.logger && this.logger.level) {
2235
+ return this.logger.level;
2236
+ }
2237
+ const levels = LoggerInstance["logLevels"];
2238
+ if (levels) {
2239
+ return levels.find((level) => level !== "verbose");
2240
+ }
2241
+ return "warn";
2124
2242
  }
2125
2243
  };
2126
2244
 
2127
- // packages/core/src/services/guard-runner.service.mts
2128
- var _GuardRunnerService_decorators, _init5;
2129
- _GuardRunnerService_decorators = [Injectable()];
2130
- var GuardRunnerService = class {
2131
- async runGuards(allGuards, executionContext) {
2132
- let canActivate = true;
2133
- for (const guard of Array.from(allGuards).reverse()) {
2134
- const guardInstance = await inject(
2135
- guard
2136
- );
2137
- if (!guardInstance.canActivate) {
2138
- throw new Error(
2139
- `[Navios] Guard ${guard.name} does not implement canActivate()`
2140
- );
2141
- }
2142
- try {
2143
- canActivate = await guardInstance.canActivate(executionContext);
2144
- if (!canActivate) {
2145
- break;
2146
- }
2147
- } catch (error) {
2148
- if (error instanceof HttpException) {
2149
- executionContext.getReply().status(error.statusCode).send(error.response);
2150
- return false;
2151
- } else {
2152
- executionContext.getReply().status(500).send({
2153
- message: "Internal server error",
2154
- error: error.message
2155
- });
2156
- return false;
2157
- }
2158
- }
2159
- }
2160
- if (!canActivate) {
2161
- executionContext.getReply().status(403).send({
2162
- message: "Forbidden"
2163
- });
2164
- return false;
2165
- }
2166
- return canActivate;
2245
+ // packages/core/src/config/config.service.mts
2246
+ import { NaviosException as NaviosException4 } from "@navios/common";
2247
+ var ConfigServiceInstance = class {
2248
+ constructor(config = {}, logger) {
2249
+ this.config = config;
2250
+ this.logger = logger;
2167
2251
  }
2168
- makeContext(executionContext) {
2169
- const guards = /* @__PURE__ */ new Set();
2170
- const endpointGuards = executionContext.getHandler().guards;
2171
- const controllerGuards = executionContext.getController().guards;
2172
- const moduleGuards = executionContext.getModule().guards;
2173
- if (endpointGuards.size > 0) {
2174
- for (const guard of endpointGuards) {
2175
- guards.add(guard);
2176
- }
2177
- }
2178
- if (controllerGuards.size > 0) {
2179
- for (const guard of controllerGuards) {
2180
- guards.add(guard);
2252
+ getConfig() {
2253
+ return this.config;
2254
+ }
2255
+ get(key) {
2256
+ var _a, _b;
2257
+ try {
2258
+ const parts = String(key).split(".");
2259
+ let value = this.config;
2260
+ for (const part of parts) {
2261
+ if (value === null || value === void 0 || typeof value !== "object") {
2262
+ return null;
2263
+ }
2264
+ value = value[part];
2181
2265
  }
2266
+ return value ?? null;
2267
+ } catch (error) {
2268
+ (_b = (_a = this.logger).debug) == null ? void 0 : _b.call(
2269
+ _a,
2270
+ `Failed to get config value for key ${String(key)}`,
2271
+ error
2272
+ );
2273
+ return null;
2182
2274
  }
2183
- if (moduleGuards.size > 0) {
2184
- for (const guard of moduleGuards) {
2185
- guards.add(guard);
2186
- }
2275
+ }
2276
+ getOrDefault(key, defaultValue) {
2277
+ const value = this.get(key);
2278
+ return value !== null ? value : defaultValue;
2279
+ }
2280
+ getOrThrow(key, errorMessage) {
2281
+ const value = this.get(key);
2282
+ if (value === null) {
2283
+ const message = errorMessage || `Configuration value for key "${String(key)}" is not defined`;
2284
+ this.logger.error(message);
2285
+ throw new NaviosException4(message);
2187
2286
  }
2188
- return guards;
2287
+ return value;
2189
2288
  }
2190
2289
  };
2191
- _init5 = __decoratorStart(null);
2192
- GuardRunnerService = __decorateElement(_init5, 0, "GuardRunnerService", _GuardRunnerService_decorators, GuardRunnerService);
2193
- __runInitializers(_init5, 1, GuardRunnerService);
2194
2290
 
2195
- // packages/core/src/services/controller-adapter.service.mts
2196
- var _ControllerAdapterService_decorators, _init6;
2197
- _ControllerAdapterService_decorators = [Injectable()];
2198
- var _ControllerAdapterService = class _ControllerAdapterService {
2199
- guardRunner = syncInject(GuardRunnerService);
2291
+ // packages/core/src/config/config.provider.mts
2292
+ var ConfigProviderOptions = z3.object({
2293
+ load: z3.function()
2294
+ });
2295
+ var ConfigProvider = InjectionToken.create(ConfigServiceInstance, ConfigProviderOptions);
2296
+ var _ConfigProviderFactory_decorators, _init7;
2297
+ _ConfigProviderFactory_decorators = [Injectable({
2298
+ token: ConfigProvider,
2299
+ type: "Factory" /* Factory */
2300
+ })];
2301
+ var ConfigProviderFactory = class {
2200
2302
  logger = syncInject(Logger, {
2201
- context: _ControllerAdapterService.name
2303
+ context: "ConfigService"
2202
2304
  });
2203
- setupController(controller, instance, moduleMetadata) {
2204
- const controllerMetadata = extractControllerMetadata(controller);
2205
- for (const endpoint of controllerMetadata.endpoints) {
2206
- const { classMethod, url, httpMethod } = endpoint;
2207
- if (!url) {
2208
- throw new Error(
2209
- `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`
2210
- );
2211
- }
2212
- const executionContext = new ExecutionContext2(
2213
- moduleMetadata,
2214
- controllerMetadata,
2215
- endpoint
2216
- );
2217
- instance.withTypeProvider().route({
2218
- method: httpMethod,
2219
- url: url.replaceAll("$", ":"),
2220
- schema: this.provideSchemaForConfig(endpoint),
2221
- preHandler: this.providePreHandler(executionContext),
2222
- handler: this.provideHandler(controller, executionContext, endpoint)
2223
- });
2224
- this.logger.debug(
2225
- `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`
2226
- );
2305
+ async create(ctx, args) {
2306
+ const { load } = args;
2307
+ const logger = this.logger;
2308
+ try {
2309
+ const config = await load();
2310
+ return new ConfigServiceInstance(config, logger);
2311
+ } catch (error) {
2312
+ logger.error("Error loading config", error);
2313
+ throw error;
2227
2314
  }
2228
2315
  }
2229
- providePreHandler(executionContext) {
2230
- const guards = this.guardRunner.makeContext(executionContext);
2231
- return guards.size > 0 ? async (request, reply) => {
2232
- getServiceLocator().registerInstance(Request, request);
2233
- getServiceLocator().registerInstance(Reply, reply);
2234
- getServiceLocator().registerInstance(
2235
- ExecutionContextToken,
2236
- executionContext
2316
+ };
2317
+ _init7 = __decoratorStart(null);
2318
+ ConfigProviderFactory = __decorateElement(_init7, 0, "ConfigProviderFactory", _ConfigProviderFactory_decorators, ConfigProviderFactory);
2319
+ __runInitializers(_init7, 1, ConfigProviderFactory);
2320
+ function provideConfig(options) {
2321
+ return InjectionToken.bound(ConfigProvider, options);
2322
+ }
2323
+
2324
+ // packages/core/src/decorators/controller.decorator.mts
2325
+ function Controller({ guards } = {}) {
2326
+ return function(target, context) {
2327
+ if (context.kind !== "class") {
2328
+ throw new Error(
2329
+ "[Navios] @Controller decorator can only be used on classes."
2237
2330
  );
2238
- executionContext.provideRequest(request);
2239
- executionContext.provideReply(reply);
2240
- let canActivate = true;
2241
- try {
2242
- canActivate = await this.guardRunner.runGuards(
2243
- guards,
2244
- executionContext
2245
- );
2246
- } finally {
2247
- getServiceLocator().removeInstance(Request);
2248
- getServiceLocator().removeInstance(Reply);
2249
- getServiceLocator().removeInstance(ExecutionContextToken);
2250
- }
2251
- if (!canActivate) {
2252
- return reply;
2253
- }
2254
- } : void 0;
2255
- }
2256
- provideSchemaForConfig(endpointMetadata) {
2257
- if (!endpointMetadata.config) {
2258
- this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`);
2259
- return {};
2260
2331
  }
2261
- const { querySchema, requestSchema, responseSchema } = endpointMetadata.config;
2262
- const schema = {};
2263
- if (querySchema) {
2264
- schema.querystring = querySchema;
2332
+ const token = InjectionToken.create(target);
2333
+ if (context.metadata) {
2334
+ const controllerMetadata = getControllerMetadata(target, context);
2335
+ if (guards) {
2336
+ for (const guard of Array.from(guards).reverse()) {
2337
+ controllerMetadata.guards.add(guard);
2338
+ }
2339
+ }
2265
2340
  }
2266
- if (requestSchema && endpointMetadata.type !== "multipart" /* Multipart */) {
2267
- schema.body = requestSchema;
2341
+ return Injectable({
2342
+ token,
2343
+ type: "Class" /* Class */,
2344
+ scope: "Instance" /* Instance */
2345
+ })(target, context);
2346
+ };
2347
+ }
2348
+
2349
+ // packages/core/src/decorators/endpoint.decorator.mts
2350
+ import "zod";
2351
+ function Endpoint(endpoint) {
2352
+ return (target, context) => {
2353
+ if (typeof target !== "function") {
2354
+ throw new Error(
2355
+ "[Navios] Endpoint decorator can only be used on functions."
2356
+ );
2268
2357
  }
2269
- if (responseSchema) {
2270
- schema.response = {
2271
- 200: responseSchema
2272
- };
2358
+ if (context.kind !== "method") {
2359
+ throw new Error(
2360
+ "[Navios] Endpoint decorator can only be used on methods."
2361
+ );
2273
2362
  }
2274
- return schema;
2275
- }
2276
- provideHandler(controller, executionContext, endpointMetadata) {
2277
- switch (endpointMetadata.type) {
2278
- case "unknown" /* Unknown */:
2279
- this.logger.error(
2280
- `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`
2281
- );
2282
- throw new NaviosException4("Unknown endpoint type");
2283
- case "endpoint" /* Endpoint */:
2284
- return this.provideHandlerForConfig(
2285
- controller,
2286
- executionContext,
2287
- endpointMetadata
2288
- );
2289
- case "stream" /* Stream */:
2290
- return this.provideHandlerForStream(
2291
- controller,
2292
- executionContext,
2293
- endpointMetadata
2294
- );
2295
- case "multipart" /* Multipart */:
2296
- return this.provideHandlerForMultipart(
2297
- controller,
2298
- executionContext,
2299
- endpointMetadata
2363
+ const config = endpoint.config;
2364
+ if (context.metadata) {
2365
+ let endpointMetadata = getEndpointMetadata(target, context);
2366
+ if (endpointMetadata.config && endpointMetadata.config.url) {
2367
+ throw new Error(
2368
+ `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2300
2369
  );
2301
- case "handler" /* Handler */:
2302
- this.logger.error("Not implemented yet");
2303
- throw new NaviosException4("Not implemented yet");
2370
+ }
2371
+ endpointMetadata.config = config;
2372
+ endpointMetadata.type = "endpoint" /* Endpoint */;
2373
+ endpointMetadata.classMethod = target.name;
2374
+ endpointMetadata.httpMethod = config.method;
2375
+ endpointMetadata.url = config.url;
2304
2376
  }
2305
- }
2306
- provideHandlerForConfig(controller, executionContext, endpointMetadata) {
2307
- return async (request, reply) => {
2308
- getServiceLocator().registerInstance(Request, request);
2309
- getServiceLocator().registerInstance(Reply, reply);
2310
- getServiceLocator().registerInstance(
2311
- ExecutionContextToken,
2312
- executionContext
2377
+ return target;
2378
+ };
2379
+ }
2380
+
2381
+ // packages/core/src/decorators/header.decorator.mts
2382
+ function Header(name2, value) {
2383
+ return (target, context) => {
2384
+ if (context.kind !== "method") {
2385
+ throw new Error("[Navios] Header decorator can only be used on methods.");
2386
+ }
2387
+ const metadata = getEndpointMetadata(target, context);
2388
+ if (metadata.type === "stream" /* Stream */) {
2389
+ throw new Error(
2390
+ "[Navios] HttpCode decorator cannot be used on stream endpoints."
2313
2391
  );
2314
- executionContext.provideRequest(request);
2315
- executionContext.provideReply(reply);
2316
- const controllerInstance = await inject(controller);
2317
- try {
2318
- const { query, params, body } = request;
2319
- const argument = {};
2320
- if (query && Object.keys(query).length > 0) {
2321
- argument.params = query;
2322
- }
2323
- if (params && Object.keys(params).length > 0) {
2324
- argument.urlParams = params;
2325
- }
2326
- if (body) {
2327
- argument.data = body;
2328
- }
2329
- const result = await controllerInstance[endpointMetadata.classMethod](argument);
2330
- reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
2331
- } finally {
2332
- getServiceLocator().removeInstance(Request);
2333
- getServiceLocator().removeInstance(Reply);
2334
- getServiceLocator().removeInstance(ExecutionContextToken);
2335
- }
2336
- };
2337
- }
2338
- provideHandlerForStream(controller, executionContext, endpointMetadata) {
2339
- return async (request, reply) => {
2340
- getServiceLocator().registerInstance(Request, request);
2341
- getServiceLocator().registerInstance(Reply, reply);
2342
- getServiceLocator().registerInstance(
2343
- ExecutionContextToken,
2344
- executionContext
2392
+ }
2393
+ metadata.headers[name2] = value;
2394
+ return target;
2395
+ };
2396
+ }
2397
+
2398
+ // packages/core/src/decorators/http-code.decorator.mts
2399
+ function HttpCode(code) {
2400
+ return (target, context) => {
2401
+ if (context.kind !== "method") {
2402
+ throw new Error(
2403
+ "[Navios] HttpCode decorator can only be used on methods."
2404
+ );
2405
+ }
2406
+ const metadata = getEndpointMetadata(target, context);
2407
+ if (metadata.type === "stream" /* Stream */) {
2408
+ throw new Error(
2409
+ "[Navios] HttpCode decorator cannot be used on stream endpoints."
2345
2410
  );
2346
- executionContext.provideRequest(request);
2347
- executionContext.provideReply(reply);
2348
- const controllerInstance = await inject(controller);
2349
- try {
2350
- const { query, params, body } = request;
2351
- const argument = {};
2352
- if (query && Object.keys(query).length > 0) {
2353
- argument.params = query;
2354
- }
2355
- if (params && Object.keys(params).length > 0) {
2356
- argument.urlParams = params;
2357
- }
2358
- if (body) {
2359
- argument.data = body;
2360
- }
2361
- await controllerInstance[endpointMetadata.classMethod](argument, reply);
2362
- } finally {
2363
- getServiceLocator().removeInstance(Request);
2364
- getServiceLocator().removeInstance(Reply);
2365
- getServiceLocator().removeInstance(ExecutionContextToken);
2411
+ }
2412
+ metadata.successStatusCode = code;
2413
+ return target;
2414
+ };
2415
+ }
2416
+
2417
+ // packages/core/src/decorators/module.decorator.mts
2418
+ function Module(metadata) {
2419
+ return (target, context) => {
2420
+ if (context.kind !== "class") {
2421
+ throw new Error("[Navios] @Module decorator can only be used on classes.");
2422
+ }
2423
+ const token = InjectionToken.create(target);
2424
+ const moduleMetadata = getModuleMetadata(target, context);
2425
+ if (metadata.controllers) {
2426
+ for (const controller of metadata.controllers) {
2427
+ moduleMetadata.controllers.add(controller);
2366
2428
  }
2367
- };
2368
- }
2369
- provideHandlerForMultipart(controller, executionContext, endpointMetadata) {
2370
- const config = endpointMetadata.config;
2371
- const requestSchema = config.requestSchema;
2372
- const shape = requestSchema._def.shape();
2373
- return async (request, reply) => {
2374
- getServiceLocator().registerInstance(Request, request);
2375
- getServiceLocator().registerInstance(Reply, reply);
2376
- getServiceLocator().registerInstance(
2377
- ExecutionContextToken,
2378
- executionContext
2379
- );
2380
- executionContext.provideRequest(request);
2381
- executionContext.provideReply(reply);
2382
- const controllerInstance = await inject(controller);
2383
- try {
2384
- const parts = request.parts();
2385
- const { query, params } = request;
2386
- const argument = {};
2387
- if (query && Object.keys(query).length > 0) {
2388
- argument.params = query;
2389
- }
2390
- if (params && Object.keys(params).length > 0) {
2391
- argument.urlParams = params;
2392
- }
2393
- const req = {};
2394
- for await (const part of parts) {
2395
- if (!shape[part.fieldname]) {
2396
- throw new NaviosException4(
2397
- `Invalid field name ${part.fieldname} for multipart request`
2398
- );
2399
- }
2400
- const schema = shape[part.fieldname];
2401
- if (part.type === "file") {
2402
- const file = new File([await part.toBuffer()], part.filename, {
2403
- type: part.mimetype
2404
- });
2405
- if (schema instanceof ZodArray) {
2406
- if (!req[part.fieldname]) {
2407
- req[part.fieldname] = [];
2408
- }
2409
- req[part.fieldname].push(file);
2410
- } else {
2411
- req[part.fieldname] = file;
2412
- }
2413
- } else {
2414
- if (schema instanceof ZodArray) {
2415
- if (!req[part.fieldname]) {
2416
- req[part.fieldname] = [];
2417
- }
2418
- req[part.fieldname].push(part.value);
2419
- } else {
2420
- req[part.fieldname] = part.value;
2421
- }
2422
- }
2423
- }
2424
- argument.body = requestSchema.parse(req);
2425
- const result = await controllerInstance[endpointMetadata.classMethod](argument);
2426
- reply.status(endpointMetadata.successStatusCode).headers(endpointMetadata.headers).send(result);
2427
- } finally {
2428
- getServiceLocator().removeInstance(Request);
2429
- getServiceLocator().removeInstance(Reply);
2430
- getServiceLocator().removeInstance(ExecutionContextToken);
2429
+ }
2430
+ if (metadata.imports) {
2431
+ for (const importedModule of metadata.imports) {
2432
+ moduleMetadata.imports.add(importedModule);
2431
2433
  }
2432
- };
2433
- }
2434
- };
2435
- _init6 = __decoratorStart(null);
2436
- _ControllerAdapterService = __decorateElement(_init6, 0, "ControllerAdapterService", _ControllerAdapterService_decorators, _ControllerAdapterService);
2437
- __runInitializers(_init6, 1, _ControllerAdapterService);
2438
- var ControllerAdapterService = _ControllerAdapterService;
2434
+ }
2435
+ if (metadata.guards) {
2436
+ for (const guard of Array.from(metadata.guards).reverse()) {
2437
+ moduleMetadata.guards.add(guard);
2438
+ }
2439
+ }
2440
+ return Injectable({
2441
+ token,
2442
+ type: "Class" /* Class */,
2443
+ scope: "Singleton" /* Singleton */
2444
+ })(target, context);
2445
+ };
2446
+ }
2439
2447
 
2440
- // packages/core/src/services/module-loader.service.mts
2441
- var _ModuleLoaderService_decorators, _init7;
2442
- _ModuleLoaderService_decorators = [Injectable()];
2443
- var _ModuleLoaderService = class _ModuleLoaderService {
2444
- logger = syncInject(Logger, {
2445
- context: _ModuleLoaderService.name
2446
- });
2447
- modulesMetadata = /* @__PURE__ */ new Map();
2448
- loadedModules = /* @__PURE__ */ new Map();
2449
- initialized = false;
2450
- async loadModules(appModule) {
2451
- if (this.initialized) {
2452
- return;
2448
+ // packages/core/src/decorators/multipart.decorator.mts
2449
+ import "zod";
2450
+ function Multipart(endpoint) {
2451
+ return (target, context) => {
2452
+ if (typeof target !== "function") {
2453
+ throw new Error(
2454
+ "[Navios] Endpoint decorator can only be used on functions."
2455
+ );
2453
2456
  }
2454
- await this.traverseModules(appModule);
2455
- this.initialized = true;
2456
- }
2457
- async traverseModules(module, parentMetadata) {
2458
- const metadata = extractModuleMetadata(module);
2459
- if (parentMetadata) {
2460
- this.mergeMetadata(metadata, parentMetadata);
2457
+ if (context.kind !== "method") {
2458
+ throw new Error(
2459
+ "[Navios] Endpoint decorator can only be used on methods."
2460
+ );
2461
2461
  }
2462
- const moduleName = module.name;
2463
- if (this.modulesMetadata.has(moduleName)) {
2464
- return;
2462
+ const config = endpoint.config;
2463
+ if (context.metadata) {
2464
+ let endpointMetadata = getEndpointMetadata(target, context);
2465
+ if (endpointMetadata.config && endpointMetadata.config.url) {
2466
+ throw new Error(
2467
+ `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2468
+ );
2469
+ }
2470
+ endpointMetadata.config = config;
2471
+ endpointMetadata.type = "multipart" /* Multipart */;
2472
+ endpointMetadata.classMethod = target.name;
2473
+ endpointMetadata.httpMethod = config.method;
2474
+ endpointMetadata.url = config.url;
2465
2475
  }
2466
- this.modulesMetadata.set(moduleName, metadata);
2467
- const imports = metadata.imports ?? /* @__PURE__ */ new Set();
2468
- const loadingPromises = Array.from(imports).map(
2469
- async (importedModule) => this.traverseModules(importedModule, metadata)
2470
- );
2471
- await Promise.all(loadingPromises);
2472
- const instance = await inject(module);
2473
- if (instance.onModuleInit) {
2474
- await instance.onModuleInit();
2476
+ return target;
2477
+ };
2478
+ }
2479
+
2480
+ // packages/core/src/decorators/stream.decorator.mts
2481
+ function Stream(endpoint) {
2482
+ return (target, context) => {
2483
+ if (typeof target !== "function") {
2484
+ throw new Error(
2485
+ "[Navios] Endpoint decorator can only be used on functions."
2486
+ );
2475
2487
  }
2476
- this.logger.debug(`Module ${moduleName} loaded`);
2477
- this.loadedModules.set(moduleName, instance);
2478
- }
2479
- mergeMetadata(metadata, parentMetadata) {
2480
- if (parentMetadata.guards) {
2481
- for (const guard of parentMetadata.guards) {
2482
- metadata.guards.add(guard);
2488
+ if (context.kind !== "method") {
2489
+ throw new Error(
2490
+ "[Navios] Endpoint decorator can only be used on methods."
2491
+ );
2492
+ }
2493
+ const config = endpoint.config;
2494
+ if (context.metadata) {
2495
+ let endpointMetadata = getEndpointMetadata(target, context);
2496
+ if (endpointMetadata.config && endpointMetadata.config.url) {
2497
+ throw new Error(
2498
+ `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`
2499
+ );
2483
2500
  }
2501
+ endpointMetadata.config = config;
2502
+ endpointMetadata.type = "stream" /* Stream */;
2503
+ endpointMetadata.classMethod = target.name;
2504
+ endpointMetadata.httpMethod = config.method;
2505
+ endpointMetadata.url = config.url;
2484
2506
  }
2485
- if (parentMetadata.customAttributes) {
2486
- for (const [key, value] of parentMetadata.customAttributes) {
2487
- if (metadata.customAttributes.has(key)) {
2488
- continue;
2489
- }
2490
- metadata.customAttributes.set(key, value);
2507
+ return target;
2508
+ };
2509
+ }
2510
+
2511
+ // packages/core/src/decorators/use-guards.decorator.mts
2512
+ function UseGuards(...guards) {
2513
+ return function(target, context) {
2514
+ if (context.kind === "class") {
2515
+ const controllerMetadata = getControllerMetadata(
2516
+ target,
2517
+ context
2518
+ );
2519
+ for (const guard of guards.reverse()) {
2520
+ controllerMetadata.guards.add(guard);
2491
2521
  }
2522
+ } else if (context.kind === "method") {
2523
+ const endpointMetadata = getEndpointMetadata(target, context);
2524
+ for (const guard of guards.reverse()) {
2525
+ endpointMetadata.guards.add(guard);
2526
+ }
2527
+ } else {
2528
+ throw new Error(
2529
+ "[Navios] @UseGuards decorator can only be used on classes or methods."
2530
+ );
2492
2531
  }
2493
- }
2494
- getAllModules() {
2495
- return this.modulesMetadata;
2496
- }
2497
- dispose() {
2498
- this.modulesMetadata.clear();
2499
- this.loadedModules.clear();
2500
- this.initialized = false;
2501
- }
2502
- };
2503
- _init7 = __decoratorStart(null);
2504
- _ModuleLoaderService = __decorateElement(_init7, 0, "ModuleLoaderService", _ModuleLoaderService_decorators, _ModuleLoaderService);
2505
- __runInitializers(_init7, 1, _ModuleLoaderService);
2506
- var ModuleLoaderService = _ModuleLoaderService;
2532
+ return target;
2533
+ };
2534
+ }
2507
2535
 
2508
2536
  // packages/core/src/attribute.factory.mts
2509
2537
  var AttributeFactory = class {
@@ -2778,7 +2806,7 @@ export {
2778
2806
  EndpointType,
2779
2807
  ErrorsEnum,
2780
2808
  EventEmitter,
2781
- ExecutionContext2 as ExecutionContext,
2809
+ ExecutionContext,
2782
2810
  ExecutionContextInjectionToken,
2783
2811
  ExecutionContextToken,
2784
2812
  FactoryInjectionToken,