@navios/core 0.1.5 → 0.1.7
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/_tsup-dts-rollup.d.mts +1485 -0
- package/dist/_tsup-dts-rollup.d.ts +1485 -0
- package/dist/index.d.mts +134 -940
- package/dist/index.d.ts +134 -940
- package/dist/index.js +19 -1
- package/dist/index.mjs +19 -1
- package/package.json +4 -4
- package/src/__tests__/controller.spec.mts +2 -2
- package/src/decorators/endpoint.decorator.mts +1 -1
- package/src/navios.application.mts +17 -0
- package/src/services/module-loader.service.mts +5 -0
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../packages/core/src/index.mts","../../../../packages/core/src/config/utils/helpers.mts","../../../../packages/core/src/config/config.provider.mts","../../../../packages/core/src/logger/utils/cli-colors.util.mts","../../../../packages/core/src/logger/log-levels.mts","../../../../packages/core/src/logger/utils/is-log-level.util.mts","../../../../packages/core/src/logger/utils/filter-log-levelts.util.mts","../../../../packages/core/src/logger/utils/is-log-level-enabled.mts","../../../../packages/core/src/logger/utils/shared.utils.mts","../../../../packages/core/src/logger/console-logger.service.mts","../../../../packages/core/src/service-locator/decorators/injectable.decorator.mts","../../../../packages/core/src/service-locator/enums/injectable-scope.enum.mts","../../../../packages/core/src/service-locator/injection-token.mts","../../../../packages/core/src/service-locator/errors/errors.enum.mts","../../../../packages/core/src/service-locator/errors/factory-not-found.mts","../../../../packages/core/src/service-locator/errors/factory-token-not-resolved.mts","../../../../packages/core/src/service-locator/errors/instance-destroying.mts","../../../../packages/core/src/service-locator/errors/instance-expired.mts","../../../../packages/core/src/service-locator/errors/instance-not-found.mts","../../../../packages/core/src/service-locator/errors/unknown-error.mts","../../../../packages/core/src/service-locator/service-locator-event-bus.mts","../../../../packages/core/src/service-locator/service-locator-instance-holder.mts","../../../../packages/core/src/service-locator/service-locator-manager.mts","../../../../packages/core/src/service-locator/service-locator.mts","../../../../packages/core/src/service-locator/injector.mts","../../../../packages/core/src/service-locator/resolve-service.mts","../../../../packages/core/src/service-locator/proxy-service-locator.mts","../../../../packages/core/src/service-locator/sync-injector.mts","../../../../packages/core/src/service-locator/decorators/get-injectable-token.mts","../../../../packages/core/src/service-locator/event-emitter.mts","../../../../packages/core/src/service-locator/inject.mts","../../../../packages/core/src/service-locator/override.mts","../../../../packages/core/src/logger/logger.factory.mts","../../../../packages/core/src/logger/logger.service.mts","../../../../packages/core/src/logger/pino-wrapper.mts","../../../../packages/core/src/config/config.service.mts","../../../../packages/core/src/metadata/endpoint.metadata.mts","../../../../packages/core/src/metadata/controller.metadata.mts","../../../../packages/core/src/metadata/module.metadata.mts","../../../../packages/core/src/decorators/controller.decorator.mts","../../../../packages/core/src/decorators/endpoint.decorator.mts","../../../../packages/core/src/decorators/header.decorator.mts","../../../../packages/core/src/decorators/http-code.decorator.mts","../../../../packages/core/src/decorators/module.decorator.mts","../../../../packages/core/src/decorators/use-guards.decorator.mts","../../../../packages/core/src/exceptions/http.exception.mts","../../../../packages/core/src/exceptions/bad-request.exception.mts","../../../../packages/core/src/exceptions/forbidden.exception.mts","../../../../packages/core/src/exceptions/internal-server-error.exception.mts","../../../../packages/core/src/exceptions/not-found.exception.mts","../../../../packages/core/src/exceptions/unauthorized.exception.mts","../../../../packages/core/src/exceptions/conflict.exception.mts","../../../../packages/core/src/services/controller-adapter.service.mts","../../../../packages/core/src/tokens/application.token.mts","../../../../packages/core/src/tokens/execution-context.token.mts","../../../../packages/core/src/tokens/reply.token.mts","../../../../packages/core/src/tokens/request.token.mts","../../../../packages/core/src/services/execution-context.mts","../../../../packages/core/src/services/guard-runner.service.mts","../../../../packages/core/src/services/module-loader.service.mts","../../../../packages/core/src/attribute.factory.mts","../../../../packages/core/src/navios.application.mts","../../../../packages/core/src/navios.factory.mts"],"sourcesContent":["export * from './config/index.mjs'\nexport * from './decorators/index.mjs'\nexport * from './exceptions/index.mjs'\nexport * from './interfaces/index.mjs'\nexport * from './logger/index.mjs'\nexport * from './metadata/index.mjs'\nexport * from './service-locator/index.mjs'\nexport * from './services/index.mjs'\nexport * from './tokens/index.mjs'\nexport * from './attribute.factory.mjs'\nexport * from './navios.application.mjs'\nexport * from './navios.factory.mjs'\n","import { env } from 'node:process'\n\nexport function envInt(\n key: keyof NodeJS.ProcessEnv,\n defaultValue: number,\n): number {\n const envKey = env[key] || process.env[key]\n\n return envKey ? parseInt(envKey as string, 10) : defaultValue\n}\n\nexport function envString<\n DefaultValue extends string | undefined,\n Ensured = DefaultValue extends string ? true : false,\n>(\n key: keyof NodeJS.ProcessEnv,\n defaultValue?: DefaultValue,\n): Ensured extends true ? string : string | undefined {\n return (env[key] ||\n process.env[key] ||\n defaultValue ||\n undefined) as Ensured extends true ? string : string | undefined\n}\n","import { z } from 'zod'\n\nimport type { ConfigService } from './config-service.interface.mjs'\n\nimport { Logger } from '../logger/index.mjs'\nimport {\n Injectable,\n InjectableType,\n InjectionToken,\n syncInject,\n} from '../service-locator/index.mjs'\nimport { ConfigServiceInstance } from './config.service.mjs'\n\nexport const ConfigProviderOptions = z.object({\n load: z.function(),\n})\n\nexport const ConfigProvider = InjectionToken.create<\n ConfigService,\n typeof ConfigProviderOptions\n>(ConfigServiceInstance, ConfigProviderOptions)\n\n@Injectable({\n token: ConfigProvider,\n type: InjectableType.Factory,\n})\nexport class ConfigProviderFactory {\n logger = syncInject(Logger, {\n context: 'ConfigService',\n })\n\n async create(ctx: any, args: z.infer<typeof ConfigProviderOptions>) {\n const { load } = args\n const logger = this.logger\n try {\n const config = await load()\n\n return new ConfigServiceInstance(config, logger)\n } catch (error) {\n logger.error('Error loading config', error)\n throw error\n }\n }\n}\n\nexport function provideConfig<ConfigMap extends Record<string, unknown>>(\n options: z.input<typeof ConfigProviderOptions>,\n) {\n return InjectionToken.bound(ConfigProvider, options) as InjectionToken<\n ConfigServiceInstance<ConfigMap>,\n undefined\n >\n}\n","type ColorTextFn = (text: string) => string\n\nconst isColorAllowed = () => !process.env.NO_COLOR\nconst colorIfAllowed = (colorFn: ColorTextFn) => (text: string) =>\n isColorAllowed() ? colorFn(text) : text\n\nexport const clc = {\n bold: colorIfAllowed((text: string) => `\\x1B[1m${text}\\x1B[0m`),\n green: colorIfAllowed((text: string) => `\\x1B[32m${text}\\x1B[39m`),\n yellow: colorIfAllowed((text: string) => `\\x1B[33m${text}\\x1B[39m`),\n red: colorIfAllowed((text: string) => `\\x1B[31m${text}\\x1B[39m`),\n magentaBright: colorIfAllowed((text: string) => `\\x1B[95m${text}\\x1B[39m`),\n cyanBright: colorIfAllowed((text: string) => `\\x1B[96m${text}\\x1B[39m`),\n}\nexport const yellow = colorIfAllowed(\n (text: string) => `\\x1B[38;5;3m${text}\\x1B[39m`,\n)\n","export const LOG_LEVELS = [\n 'verbose',\n 'debug',\n 'log',\n 'warn',\n 'error',\n 'fatal',\n] as const satisfies string[]\n/**\n * @publicApi\n */\nexport type LogLevel = (typeof LOG_LEVELS)[number]\n","import type { LogLevel } from '../log-levels.mjs'\n\nimport { LOG_LEVELS } from '../log-levels.mjs'\n\n/**\n * @publicApi\n */\nexport function isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel {\n return LOG_LEVELS.includes(maybeLogLevel)\n}\n","import type { LogLevel } from '../log-levels.mjs'\n\nimport { LOG_LEVELS } from '../log-levels.mjs'\nimport { isLogLevel } from './is-log-level.util.mjs'\n\n/**\n * @publicApi\n */\nexport function filterLogLevels(parseableString = ''): LogLevel[] {\n const sanitizedString = parseableString.replaceAll(' ', '').toLowerCase()\n\n if (sanitizedString[0] === '>') {\n const orEqual = sanitizedString[1] === '='\n\n const logLevelIndex = (LOG_LEVELS as string[]).indexOf(\n sanitizedString.substring(orEqual ? 2 : 1),\n )\n\n if (logLevelIndex === -1) {\n throw new Error(`parse error (unknown log level): ${sanitizedString}`)\n }\n\n return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1)\n } else if (sanitizedString.includes(',')) {\n return sanitizedString.split(',').filter(isLogLevel)\n }\n\n return isLogLevel(sanitizedString) ? [sanitizedString] : LOG_LEVELS\n}\n","import type { LogLevel } from '../log-levels.mjs'\n\nconst LOG_LEVEL_VALUES: Record<LogLevel, number> = {\n verbose: 0,\n debug: 1,\n log: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n}\n\n/**\n * Checks if target level is enabled.\n * @param targetLevel target level\n * @param logLevels array of enabled log levels\n */\nexport function isLogLevelEnabled(\n targetLevel: LogLevel,\n logLevels: LogLevel[] | undefined,\n): boolean {\n if (!logLevels || (Array.isArray(logLevels) && logLevels?.length === 0)) {\n return false\n }\n if (logLevels.includes(targetLevel)) {\n return true\n }\n const highestLogLevelValue = logLevels\n .map((level) => LOG_LEVEL_VALUES[level])\n .sort((a, b) => b - a)?.[0]\n\n const targetLevelValue = LOG_LEVEL_VALUES[targetLevel]\n return targetLevelValue >= highestLogLevelValue\n}\n","export const isUndefined = (obj: any): obj is undefined =>\n typeof obj === 'undefined'\n\nexport const isObject = (fn: any): fn is object =>\n !isNil(fn) && typeof fn === 'object'\n\nexport const isPlainObject = (fn: any): fn is object => {\n if (!isObject(fn)) {\n return false\n }\n const proto = Object.getPrototypeOf(fn)\n if (proto === null) {\n return true\n }\n const ctor =\n Object.prototype.hasOwnProperty.call(proto, 'constructor') &&\n proto.constructor\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) ===\n Function.prototype.toString.call(Object)\n )\n}\n\nexport const addLeadingSlash = (path?: string): string =>\n path && typeof path === 'string'\n ? path.charAt(0) !== '/' && path.substring(0, 2) !== '{/'\n ? '/' + path\n : path\n : ''\n\nexport const normalizePath = (path?: string): string =>\n path\n ? path.startsWith('/')\n ? ('/' + path.replace(/\\/+$/, '')).replace(/\\/+/g, '/')\n : '/' + path.replace(/\\/+$/, '')\n : '/'\n\nexport const stripEndSlash = (path: string) =>\n path[path.length - 1] === '/' ? path.slice(0, path.length - 1) : path\n\nexport const isFunction = (val: any): val is Function =>\n typeof val === 'function'\nexport const isString = (val: any): val is string => typeof val === 'string'\nexport const isNumber = (val: any): val is number => typeof val === 'number'\nexport const isConstructor = (val: any): boolean => val === 'constructor'\nexport const isNil = (val: any): val is null | undefined =>\n isUndefined(val) || val === null\nexport const isEmpty = (array: any): boolean => !(array && array.length > 0)\nexport const isSymbol = (val: any): val is symbol => typeof val === 'symbol'\n","import type { InspectOptions } from 'util'\n\nimport { inspect } from 'util'\n\nimport type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-service.interface.mjs'\n\nimport { Injectable } from '../service-locator/index.mjs'\nimport {\n clc,\n isFunction,\n isLogLevelEnabled,\n isPlainObject,\n isString,\n isUndefined,\n yellow,\n} from './utils/index.mjs'\n\nconst DEFAULT_DEPTH = 5\n\n/**\n * @publicApi\n */\nexport interface ConsoleLoggerOptions {\n /**\n * Enabled log levels.\n */\n logLevels?: LogLevel[]\n /**\n * If enabled, will print timestamp (time difference) between current and previous log message.\n * Note: This option is not used when `json` is enabled.\n */\n timestamp?: boolean\n /**\n * A prefix to be used for each log message.\n * Note: This option is not used when `json` is enabled.\n */\n prefix?: string\n /**\n * If enabled, will print the log message in JSON format.\n */\n json?: boolean\n /**\n * If enabled, will print the log message in color.\n * Default true if json is disabled, false otherwise\n */\n colors?: boolean\n /**\n * The context of the logger.\n */\n context?: string\n /**\n * If enabled, will print the log message in a single line, even if it is an object with multiple properties.\n * If set to a number, the most n inner elements are united on a single line as long as all properties fit into breakLength. Short array elements are also grouped together.\n * Default true when `json` is enabled, false otherwise.\n */\n compact?: boolean | number\n /**\n * Specifies the maximum number of Array, TypedArray, Map, Set, WeakMap, and WeakSet elements to include when formatting.\n * Set to null or Infinity to show all elements. Set to 0 or negative to show no elements.\n * Ignored when `json` is enabled, colors are disabled, and `compact` is set to true as it produces a parseable JSON output.\n * @default 100\n */\n maxArrayLength?: number\n /**\n * Specifies the maximum number of characters to include when formatting.\n * Set to null or Infinity to show all elements. Set to 0 or negative to show no characters.\n * Ignored when `json` is enabled, colors are disabled, and `compact` is set to true as it produces a parseable JSON output.\n * @default 10000.\n */\n maxStringLength?: number\n /**\n * If enabled, will sort keys while formatting objects.\n * Can also be a custom sorting function.\n * Ignored when `json` is enabled, colors are disabled, and `compact` is set to true as it produces a parseable JSON output.\n * @default false\n */\n sorted?: boolean | ((a: string, b: string) => number)\n /**\n * Specifies the number of times to recurse while formatting object. T\n * This is useful for inspecting large objects. To recurse up to the maximum call stack size pass Infinity or null.\n * Ignored when `json` is enabled, colors are disabled, and `compact` is set to true as it produces a parseable JSON output.\n * @default 5\n */\n depth?: number\n /**\n * If true, object's non-enumerable symbols and properties are included in the formatted result.\n * WeakMap and WeakSet entries are also included as well as user defined prototype properties\n * @default false\n */\n showHidden?: boolean\n /**\n * The length at which input values are split across multiple lines. Set to Infinity to format the input as a single line (in combination with \"compact\" set to true).\n * Default Infinity when \"compact\" is true, 80 otherwise.\n * Ignored when `json` is enabled, colors are disabled, and `compact` is set to true as it produces a parseable JSON output.\n */\n breakLength?: number\n}\n\nconst DEFAULT_LOG_LEVELS: LogLevel[] = [\n 'log',\n 'error',\n 'warn',\n 'debug',\n 'verbose',\n 'fatal',\n]\n\nconst dateTimeFormatter = new Intl.DateTimeFormat(undefined, {\n year: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n day: '2-digit',\n month: '2-digit',\n})\n\n/**\n * @publicApi\n */\n@Injectable()\nexport class ConsoleLogger implements LoggerService {\n /**\n * The options of the logger.\n */\n protected options: ConsoleLoggerOptions\n /**\n * The context of the logger (can be set manually or automatically inferred).\n */\n protected context?: string\n /**\n * The original context of the logger (set in the constructor).\n */\n protected originalContext?: string\n /**\n * The options used for the \"inspect\" method.\n */\n protected inspectOptions: InspectOptions\n /**\n * The last timestamp at which the log message was printed.\n */\n protected static lastTimestampAt?: number\n\n constructor()\n constructor(context: string)\n constructor(options: ConsoleLoggerOptions)\n constructor(context: string, options: ConsoleLoggerOptions)\n constructor(\n contextOrOptions?: string | ConsoleLoggerOptions,\n options?: ConsoleLoggerOptions,\n ) {\n // eslint-disable-next-line prefer-const\n let [context, opts] = isString(contextOrOptions)\n ? [contextOrOptions, options]\n : options\n ? [undefined, options]\n : [contextOrOptions?.context, contextOrOptions]\n\n opts = opts ?? {}\n opts.logLevels ??= DEFAULT_LOG_LEVELS\n opts.colors ??= opts.colors ?? (opts.json ? false : true)\n opts.prefix ??= 'Navios'\n\n this.options = opts\n this.inspectOptions = this.getInspectOptions()\n\n if (context) {\n this.context = context\n this.originalContext = context\n }\n }\n\n /**\n * Write a 'log' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n log(message: any, context?: string): void\n log(message: any, ...optionalParams: [...any, string?]): void\n log(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('log')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n this.printMessages(messages, context, 'log')\n }\n\n /**\n * Write an 'error' level log, if the configured level allows for it.\n * Prints to `stderr` with newline.\n */\n error(message: any, stackOrContext?: string): void\n error(message: any, stack?: string, context?: string): void\n error(message: any, ...optionalParams: [...any, string?, string?]): void\n error(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('error')) {\n return\n }\n const { messages, context, stack } =\n this.getContextAndStackAndMessagesToPrint([message, ...optionalParams])\n\n this.printMessages(messages, context, 'error', 'stderr', stack)\n this.printStackTrace(stack!)\n }\n\n /**\n * Write a 'warn' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n warn(message: any, context?: string): void\n warn(message: any, ...optionalParams: [...any, string?]): void\n warn(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('warn')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n this.printMessages(messages, context, 'warn')\n }\n\n /**\n * Write a 'debug' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n debug(message: any, context?: string): void\n debug(message: any, ...optionalParams: [...any, string?]): void\n debug(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('debug')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n this.printMessages(messages, context, 'debug')\n }\n\n /**\n * Write a 'verbose' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n verbose(message: any, context?: string): void\n verbose(message: any, ...optionalParams: [...any, string?]): void\n verbose(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('verbose')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n this.printMessages(messages, context, 'verbose')\n }\n\n /**\n * Write a 'fatal' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n fatal(message: any, context?: string): void\n fatal(message: any, ...optionalParams: [...any, string?]): void\n fatal(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('fatal')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n this.printMessages(messages, context, 'fatal')\n }\n\n /**\n * Set log levels\n * @param levels log levels\n */\n setLogLevels(levels: LogLevel[]) {\n if (!this.options) {\n this.options = {}\n }\n this.options.logLevels = levels\n }\n\n /**\n * Set logger context\n * @param context context\n */\n setContext(context: string) {\n this.context = context\n }\n\n /**\n * Resets the logger context to the value that was passed in the constructor.\n */\n resetContext() {\n this.context = this.originalContext\n }\n\n isLevelEnabled(level: LogLevel): boolean {\n const logLevels = this.options?.logLevels\n return isLogLevelEnabled(level, logLevels)\n }\n\n protected getTimestamp(): string {\n return dateTimeFormatter.format(Date.now())\n }\n\n protected printMessages(\n messages: unknown[],\n context = '',\n logLevel: LogLevel = 'log',\n writeStreamType?: 'stdout' | 'stderr',\n errorStack?: unknown,\n ) {\n messages.forEach((message) => {\n if (this.options.json) {\n this.printAsJson(message, {\n context,\n logLevel,\n writeStreamType,\n errorStack,\n })\n return\n }\n const pidMessage = this.formatPid(process.pid)\n const contextMessage = this.formatContext(context)\n const timestampDiff = this.updateAndGetTimestampDiff()\n const formattedLogLevel = logLevel.toUpperCase().padStart(7, ' ')\n const formattedMessage = this.formatMessage(\n logLevel,\n message,\n pidMessage,\n formattedLogLevel,\n contextMessage,\n timestampDiff,\n )\n\n process[writeStreamType ?? 'stdout'].write(formattedMessage)\n })\n }\n\n protected printAsJson(\n message: unknown,\n options: {\n context: string\n logLevel: LogLevel\n writeStreamType?: 'stdout' | 'stderr'\n errorStack?: unknown\n },\n ) {\n type JsonLogObject = {\n level: LogLevel\n pid: number\n timestamp: number\n message: unknown\n context?: string\n stack?: unknown\n }\n\n const logObject: JsonLogObject = {\n level: options.logLevel,\n pid: process.pid,\n timestamp: Date.now(),\n message,\n }\n\n if (options.context) {\n logObject.context = options.context\n }\n\n if (options.errorStack) {\n logObject.stack = options.errorStack\n }\n\n const formattedMessage =\n !this.options.colors && this.inspectOptions.compact === true\n ? JSON.stringify(logObject, this.stringifyReplacer)\n : inspect(logObject, this.inspectOptions)\n process[options.writeStreamType ?? 'stdout'].write(`${formattedMessage}\\n`)\n }\n\n protected formatPid(pid: number) {\n return `[${this.options.prefix}] ${pid} - `\n }\n\n protected formatContext(context: string): string {\n if (!context) {\n return ''\n }\n\n context = `[${context}] `\n return this.options.colors ? yellow(context) : context\n }\n\n protected formatMessage(\n logLevel: LogLevel,\n message: unknown,\n pidMessage: string,\n formattedLogLevel: string,\n contextMessage: string,\n timestampDiff: string,\n ) {\n const output = this.stringifyMessage(message, logLevel)\n pidMessage = this.colorize(pidMessage, logLevel)\n formattedLogLevel = this.colorize(formattedLogLevel, logLevel)\n return `${pidMessage}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}\\n`\n }\n\n protected stringifyMessage(message: unknown, logLevel: LogLevel): string {\n if (isFunction(message)) {\n const messageAsStr = Function.prototype.toString.call(message)\n const isClass = messageAsStr.startsWith('class ')\n if (isClass) {\n // If the message is a class, we will display the class name.\n return this.stringifyMessage(message.name, logLevel)\n }\n // If the message is a non-class function, call it and re-resolve its value.\n return this.stringifyMessage(message(), logLevel)\n }\n\n if (typeof message === 'string') {\n return this.colorize(message, logLevel)\n }\n\n const outputText = inspect(message, this.inspectOptions)\n if (isPlainObject(message)) {\n return `Object(${Object.keys(message).length}) ${outputText}`\n }\n if (Array.isArray(message)) {\n return `Array(${message.length}) ${outputText}`\n }\n return outputText\n }\n\n protected colorize(message: string, logLevel: LogLevel) {\n if (!this.options.colors || this.options.json) {\n return message\n }\n const color = this.getColorByLogLevel(logLevel)\n return color(message)\n }\n\n protected printStackTrace(stack: string) {\n if (!stack || this.options.json) {\n return\n }\n process.stderr.write(`${stack}\\n`)\n }\n\n protected updateAndGetTimestampDiff(): string {\n const includeTimestamp =\n ConsoleLogger.lastTimestampAt && this.options?.timestamp\n const result = includeTimestamp\n ? this.formatTimestampDiff(Date.now() - ConsoleLogger.lastTimestampAt!)\n : ''\n ConsoleLogger.lastTimestampAt = Date.now()\n return result\n }\n\n protected formatTimestampDiff(timestampDiff: number) {\n const formattedDiff = ` +${timestampDiff}ms`\n return this.options.colors ? yellow(formattedDiff) : formattedDiff\n }\n\n protected getInspectOptions() {\n let breakLength = this.options.breakLength\n if (typeof breakLength === 'undefined') {\n breakLength = this.options.colors\n ? this.options.compact\n ? Infinity\n : undefined\n : this.options.compact === false\n ? undefined\n : Infinity // default breakLength to Infinity if inline is not set and colors is false\n }\n\n const inspectOptions: InspectOptions = {\n depth: this.options.depth ?? DEFAULT_DEPTH,\n sorted: this.options.sorted,\n showHidden: this.options.showHidden,\n compact: this.options.compact ?? (this.options.json ? true : false),\n colors: this.options.colors,\n breakLength,\n }\n\n if (this.options.maxArrayLength) {\n inspectOptions.maxArrayLength = this.options.maxArrayLength\n }\n if (this.options.maxStringLength) {\n inspectOptions.maxStringLength = this.options.maxStringLength\n }\n\n return inspectOptions\n }\n\n protected stringifyReplacer(key: string, value: unknown) {\n // Mimic util.inspect behavior for JSON logger with compact on and colors off\n if (typeof value === 'bigint') {\n return value.toString()\n }\n if (typeof value === 'symbol') {\n return value.toString()\n }\n\n if (\n value instanceof Map ||\n value instanceof Set ||\n value instanceof Error\n ) {\n return `${inspect(value, this.inspectOptions)}`\n }\n return value\n }\n\n private getContextAndMessagesToPrint(args: unknown[]) {\n if (args?.length <= 1) {\n return { messages: args, context: this.context }\n }\n const lastElement = args[args.length - 1]\n const isContext = isString(lastElement)\n if (!isContext) {\n return { messages: args, context: this.context }\n }\n return {\n context: lastElement,\n messages: args.slice(0, args.length - 1),\n }\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]) {\n if (args.length === 2) {\n return this.isStackFormat(args[1])\n ? {\n messages: [args[0]],\n stack: args[1] as string,\n context: this.context,\n }\n : {\n messages: [args[0]],\n context: args[1] as string,\n }\n }\n\n const { messages, context } = this.getContextAndMessagesToPrint(args)\n if (messages?.length <= 1) {\n return { messages, context }\n }\n const lastElement = messages[messages.length - 1]\n const isStack = isString(lastElement)\n // https://github.com/nestjs/nest/issues/11074#issuecomment-1421680060\n if (!isStack && !isUndefined(lastElement)) {\n return { messages, context }\n }\n return {\n stack: lastElement,\n messages: messages.slice(0, messages.length - 1),\n context,\n }\n }\n\n private isStackFormat(stack: unknown) {\n if (!isString(stack) && !isUndefined(stack)) {\n return false\n }\n\n return /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(stack!)\n }\n\n private getColorByLogLevel(level: LogLevel) {\n switch (level) {\n case 'debug':\n return clc.magentaBright\n case 'warn':\n return clc.yellow\n case 'error':\n return clc.red\n case 'verbose':\n return clc.cyanBright\n case 'fatal':\n return clc.bold\n default:\n return clc.green\n }\n }\n}\n","import { NaviosException } from '@navios/common'\n\nimport type { ClassType } from '../injection-token.mjs'\n\nimport { InjectableScope } from '../enums/index.mjs'\nimport { InjectionToken } from '../injection-token.mjs'\nimport { getServiceLocator } from '../injector.mjs'\nimport { resolveService } from '../resolve-service.mjs'\n\nexport enum InjectableType {\n Class = 'Class',\n Factory = 'Factory',\n}\n\nexport interface InjectableOptions {\n scope?: InjectableScope\n type?: InjectableType\n token?: InjectionToken<any, any>\n}\n\nexport const InjectableTokenMeta = Symbol('InjectableTokenMeta')\n\nexport function Injectable({\n scope = InjectableScope.Singleton,\n type = InjectableType.Class,\n token,\n}: InjectableOptions = {}) {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error(\n '[ServiceLocator] @Injectable decorator can only be used on classes.',\n )\n }\n let injectableToken: InjectionToken<any, any> =\n token ?? InjectionToken.create(target)\n const locator = getServiceLocator()\n if (type === InjectableType.Class) {\n locator.registerAbstractFactory(\n injectableToken,\n async (ctx) => resolveService(ctx, target),\n scope,\n )\n } else if (type === InjectableType.Factory) {\n locator.registerAbstractFactory(\n injectableToken,\n async (ctx, args: any) => {\n const builder = await resolveService(ctx, target)\n if (typeof builder.create !== 'function') {\n throw new NaviosException(\n `[ServiceLocator] Factory ${target.name} does not implement the create method.`,\n )\n }\n return builder.create(ctx, args)\n },\n scope,\n )\n }\n\n // @ts-expect-error\n target[InjectableTokenMeta] = injectableToken\n\n return target\n }\n}\n","export enum InjectableScope {\n /**\n * Singleton scope: The instance is created once and shared across the application.\n */\n Singleton = 'Singleton',\n /**\n * Instance scope: A new instance is created for each injection.\n */\n Instance = 'Instance',\n}\n","import type { AnyZodObject } from 'zod'\n\nimport { randomUUID } from 'crypto'\n\nimport { z, ZodOptional } from 'zod'\n\nexport type ClassType = new (...args: any[]) => any\n\nexport type ClassTypeWithInstance<T> = new (...args: any[]) => T\n\nexport class InjectionToken<\n T,\n S extends AnyZodObject | ZodOptional<AnyZodObject> | unknown = unknown,\n> {\n public id = randomUUID()\n constructor(\n public readonly name: string | symbol | ClassType,\n public readonly schema: AnyZodObject | undefined,\n ) {}\n\n static create<T extends ClassType>(\n name: T,\n ): InjectionToken<InstanceType<T>, undefined>\n static create<\n T extends ClassType,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject>,\n >(name: T, schema: Schema): InjectionToken<InstanceType<T>, Schema>\n static create<T>(name: string | symbol): InjectionToken<T, undefined>\n static create<T, Schema extends AnyZodObject | ZodOptional<AnyZodObject>>(\n name: string | any,\n schema: Schema,\n ): InjectionToken<T, Schema>\n static create(name: string | symbol, schema?: unknown) {\n // @ts-expect-error\n return new InjectionToken(name, schema)\n }\n\n static bound<T, S extends AnyZodObject | ZodOptional<AnyZodObject>>(\n token: InjectionToken<T, S>,\n value: z.input<S>,\n ): BoundInjectionToken<T, S> {\n return new BoundInjectionToken(token, value)\n }\n\n static factory<T, S extends AnyZodObject | ZodOptional<AnyZodObject>>(\n token: InjectionToken<T, S>,\n factory: () => Promise<z.input<S>>,\n ): FactoryInjectionToken<T, S> {\n return new FactoryInjectionToken(token, factory)\n }\n\n static refineType<T>(\n token: BoundInjectionToken<any, any>,\n ): BoundInjectionToken<T, any> {\n return token as BoundInjectionToken<T, any>\n }\n}\n\nexport class BoundInjectionToken<\n T,\n S extends AnyZodObject | ZodOptional<AnyZodObject>,\n> extends InjectionToken<T, undefined> {\n constructor(\n public readonly token: InjectionToken<T, S>,\n public readonly value: z.input<S>,\n ) {\n super(token.name, token.schema)\n this.id = token.id\n }\n}\n\nexport class FactoryInjectionToken<\n T,\n S extends AnyZodObject | ZodOptional<AnyZodObject>,\n> extends InjectionToken<T, S> {\n public value?: z.input<S>\n public resolved = false\n constructor(\n public readonly token: InjectionToken<T, S>,\n public readonly factory: () => Promise<z.input<S>>,\n ) {\n super(token.name, token.schema)\n }\n\n async resolve(): Promise<z.input<S>> {\n if (!this.value) {\n this.value = await this.factory()\n this.resolved = true\n }\n return this.value\n }\n}\n","export enum ErrorsEnum {\n InstanceExpired = 'InstanceExpired',\n InstanceNotFound = 'InstanceNotFound',\n InstanceDestroying = 'InstanceDestroying',\n UnknownError = 'UnknownError',\n FactoryNotFound = 'FactoryNotFound',\n FactoryTokenNotResolved = 'FactoryTokenNotResolved',\n}\n","import { ErrorsEnum } from './errors.enum.mjs'\n\nexport class FactoryNotFound extends Error {\n code = ErrorsEnum.FactoryNotFound\n constructor(public name: string) {\n super(`Factory ${name} not found`)\n }\n}\n","import type { ClassType } from '../injection-token.mjs'\n\nimport { ErrorsEnum } from './errors.enum.mjs'\n\nexport class FactoryTokenNotResolved extends Error {\n code = ErrorsEnum.FactoryTokenNotResolved\n constructor(name: string | symbol | ClassType) {\n super(`Factory token not resolved: ${name.toString()}`)\n }\n}\n","import { ErrorsEnum } from './errors.enum.mjs'\n\nexport class InstanceDestroying extends Error {\n code = ErrorsEnum.InstanceDestroying\n constructor(public name: string) {\n super(`Instance ${name} destroying`)\n }\n}\n","import { ErrorsEnum } from './errors.enum.mjs'\n\nexport class InstanceExpired extends Error {\n code = ErrorsEnum.InstanceExpired\n constructor(public name: string) {\n super(`Instance ${name} expired`)\n }\n}\n","import { ErrorsEnum } from './errors.enum.mjs'\n\nexport class InstanceNotFound extends Error {\n code = ErrorsEnum.InstanceNotFound\n constructor(public name: string) {\n super(`Instance ${name} not found`)\n }\n}\n","import { ErrorsEnum } from './errors.enum.mjs'\n\nexport class UnknownError extends Error {\n code = ErrorsEnum.UnknownError\n parent?: Error\n\n constructor(message: string | Error) {\n if (message instanceof Error) {\n super(message.message)\n this.parent = message\n return\n }\n super(message)\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-object-type */\n/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n\ntype ListenersMap = Map<string, Map<string, Set<Function>>>\n\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\nexport class ServiceLocatorEventBus {\n private listeners: ListenersMap = new Map()\n constructor(private readonly logger: Console | null = null) {}\n\n on<Event extends string | `pre:${string}` | `post:${string}`>(\n ns: string,\n event: Event,\n listener: (event: Event) => void,\n ) {\n this.logger?.debug(`[ServiceLocatorEventBus]#on(): ns:${ns} event:${event}`)\n if (!this.listeners.has(ns)) {\n this.listeners.set(ns, new Map())\n }\n\n const nsEvents = this.listeners.get(ns)!\n if (!nsEvents.has(event)) {\n nsEvents.set(event, new Set())\n }\n\n nsEvents.get(event)!.add(listener)\n\n return () => {\n nsEvents.get(event)!.delete(listener)\n if (nsEvents.get(event)?.size === 0) {\n nsEvents.delete(event)\n }\n if (nsEvents.size === 0) {\n this.listeners.delete(ns)\n }\n }\n }\n\n async emit(key: string, event: string) {\n if (!this.listeners.has(key)) {\n return\n }\n\n const events = this.listeners.get(key)!\n\n const preEvent = `pre:${event}`\n const postEvent = `post:${event}`\n this.logger?.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${preEvent}`)\n await Promise.allSettled(\n [...(events.get(preEvent) ?? [])].map((listener) => listener(preEvent)),\n ).then((results) => {\n results\n .filter((result) => result.status === 'rejected')\n .forEach((result: PromiseRejectedResult) => {\n this.logger?.warn(\n `[ServiceLocatorEventBus]#emit(): ${key}:${preEvent} rejected with`,\n result.reason,\n )\n })\n })\n this.logger?.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${event}`)\n\n const res = await Promise.allSettled(\n [...(events.get(event) ?? [])!].map((listener) => listener(event)),\n ).then((results) => {\n const res = results\n .filter((result) => result.status === 'rejected')\n .map((result: PromiseRejectedResult) => {\n this.logger?.warn(\n `[ServiceLocatorEventBus]#emit(): ${key}:${event} rejected with`,\n result.reason,\n )\n return result\n })\n\n if (res.length > 0) {\n return Promise.reject(res)\n }\n return results\n })\n this.logger?.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${postEvent}`)\n await Promise.allSettled(\n [...(events.get(postEvent) ?? [])].map((listener) => listener(postEvent)),\n ).then((results) => {\n results\n .filter((result) => result.status === 'rejected')\n .forEach((result: PromiseRejectedResult) => {\n this.logger?.warn(\n `[ServiceLocatorEventBus]#emit(): ${key}:${postEvent} rejected with`,\n result.reason,\n )\n })\n })\n return res\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-object-type */\n\nexport enum ServiceLocatorInstanceHolderKind {\n Instance = 'instance',\n Factory = 'factory',\n AbstractFactory = 'abstractFactory',\n}\n\nexport enum ServiceLocatorInstanceHolderStatus {\n Created = 'created',\n Creating = 'creating',\n Destroying = 'destroying',\n}\n\nexport type ServiceLocatorInstanceEffect = () => void\nexport type ServiceLocatorInstanceDestroyListener = () => void | Promise<void>\n\nexport interface ServiceLocatorInstanceHolderCreating<Instance> {\n status: ServiceLocatorInstanceHolderStatus.Creating\n name: string\n instance: null\n creationPromise: Promise<[undefined, Instance]> | null\n destroyPromise: null\n kind: ServiceLocatorInstanceHolderKind\n effects: ServiceLocatorInstanceEffect[]\n deps: string[]\n destroyListeners: ServiceLocatorInstanceDestroyListener[]\n createdAt: number\n ttl: number\n}\n\nexport interface ServiceLocatorInstanceHolderCreated<Instance> {\n status: ServiceLocatorInstanceHolderStatus.Created\n name: string\n instance: Instance\n creationPromise: null\n destroyPromise: null\n kind: ServiceLocatorInstanceHolderKind\n effects: ServiceLocatorInstanceEffect[]\n deps: string[]\n destroyListeners: ServiceLocatorInstanceDestroyListener[]\n createdAt: number\n ttl: number\n}\n\nexport interface ServiceLocatorInstanceHolderDestroying<Instance> {\n status: ServiceLocatorInstanceHolderStatus.Destroying\n name: string\n instance: Instance | null\n creationPromise: null\n destroyPromise: Promise<void>\n kind: ServiceLocatorInstanceHolderKind\n effects: ServiceLocatorInstanceEffect[]\n deps: string[]\n destroyListeners: ServiceLocatorInstanceDestroyListener[]\n createdAt: number\n ttl: number\n}\n\nexport type ServiceLocatorInstanceHolder<Instance = unknown> =\n | ServiceLocatorInstanceHolderCreating<Instance>\n | ServiceLocatorInstanceHolderCreated<Instance>\n | ServiceLocatorInstanceHolderDestroying<Instance>\n","/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport type { ServiceLocatorInstanceHolder } from './service-locator-instance-holder.mjs'\n\nimport {\n ErrorsEnum,\n InstanceDestroying,\n InstanceExpired,\n InstanceNotFound,\n} from './errors/index.mjs'\nimport { ServiceLocatorInstanceHolderStatus } from './service-locator-instance-holder.mjs'\n\nexport class ServiceLocatorManager {\n private readonly instancesHolders: Map<string, ServiceLocatorInstanceHolder> =\n new Map()\n\n constructor(private readonly logger: Console | null = null) {}\n\n get(\n name: string,\n ):\n | [InstanceExpired | InstanceDestroying, ServiceLocatorInstanceHolder]\n | [InstanceNotFound]\n | [undefined, ServiceLocatorInstanceHolder] {\n const holder = this.instancesHolders.get(name)\n if (holder) {\n if (holder.ttl !== Infinity) {\n const now = Date.now()\n if (now - holder.createdAt > holder.ttl) {\n this.logger?.log(\n `[ServiceLocatorManager]#getInstanceHolder() TTL expired for ${holder.name}`,\n )\n return [new InstanceExpired(holder.name), holder]\n }\n } else if (\n holder.status === ServiceLocatorInstanceHolderStatus.Destroying\n ) {\n this.logger?.log(\n `[ServiceLocatorManager]#getInstanceHolder() Instance ${holder.name} is destroying`,\n )\n return [new InstanceDestroying(holder.name), holder]\n }\n\n return [undefined, holder]\n } else {\n this.logger?.log(\n `[ServiceLocatorManager]#getInstanceHolder() Instance ${name} not found`,\n )\n return [new InstanceNotFound(name)]\n }\n }\n\n set(name: string, holder: ServiceLocatorInstanceHolder): void {\n this.instancesHolders.set(name, holder)\n }\n\n has(\n name: string,\n ): [InstanceExpired | InstanceDestroying] | [undefined, boolean] {\n const [error, holder] = this.get(name)\n if (!error) {\n return [undefined, true]\n }\n if (\n [ErrorsEnum.InstanceExpired, ErrorsEnum.InstanceDestroying].includes(\n error.code,\n )\n ) {\n return [error]\n }\n return [undefined, !!holder]\n }\n\n delete(name: string): boolean {\n return this.instancesHolders.delete(name)\n }\n\n filter(\n predicate: (\n value: ServiceLocatorInstanceHolder<any>,\n key: string,\n ) => boolean,\n ): Map<string, ServiceLocatorInstanceHolder> {\n return new Map(\n [...this.instancesHolders].filter(([key, value]) =>\n predicate(value, key),\n ),\n )\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport type { AnyZodObject, z, ZodOptional } from 'zod'\n\nimport type { ServiceLocatorAbstractFactoryContext } from './service-locator-abstract-factory-context.mjs'\nimport type { ServiceLocatorInstanceHolder } from './service-locator-instance-holder.mjs'\n\nimport { InjectableScope } from './enums/index.mjs'\nimport {\n ErrorsEnum,\n FactoryNotFound,\n FactoryTokenNotResolved,\n UnknownError,\n} from './errors/index.mjs'\nimport {\n BoundInjectionToken,\n FactoryInjectionToken,\n getInjectableToken,\n} from './index.mjs'\nimport { InjectionToken } from './injection-token.mjs'\nimport { ServiceLocatorEventBus } from './service-locator-event-bus.mjs'\nimport {\n ServiceLocatorInstanceHolderKind,\n ServiceLocatorInstanceHolderStatus,\n} from './service-locator-instance-holder.mjs'\nimport { ServiceLocatorManager } from './service-locator-manager.mjs'\n\nexport class ServiceLocator {\n private abstractFactories: Map<\n InjectionToken<any, any>,\n (ctx: ServiceLocatorAbstractFactoryContext, ...args: any) => Promise<any>\n > = new Map()\n private instanceFactories: Map<\n InjectionToken<any, any>,\n (ctx: ServiceLocatorAbstractFactoryContext, ...args: any) => Promise<any>\n > = new Map()\n\n private readonly eventBus: ServiceLocatorEventBus\n private readonly manager: ServiceLocatorManager\n\n constructor(private readonly logger: Console | null = null) {\n this.eventBus = new ServiceLocatorEventBus(logger)\n this.manager = new ServiceLocatorManager(logger)\n }\n\n getEventBus() {\n return this.eventBus\n }\n\n public registerInstance<Instance>(\n token: InjectionToken<Instance, undefined>,\n instance: Instance,\n ): void {\n const instanceName = this.getInstanceIdentifier(token, undefined)\n this.manager.set(instanceName, {\n name: instanceName,\n instance,\n status: ServiceLocatorInstanceHolderStatus.Created,\n kind: ServiceLocatorInstanceHolderKind.Instance,\n createdAt: Date.now(),\n ttl: Infinity,\n deps: [],\n destroyListeners: [],\n effects: [],\n destroyPromise: null,\n creationPromise: null,\n })\n }\n\n public removeInstance<Instance>(token: InjectionToken<Instance, undefined>) {\n const instanceName = this.getInstanceIdentifier(token, undefined)\n return this.invalidate(instanceName)\n }\n\n public registerAbstractFactory<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n factory: (\n ctx: ServiceLocatorAbstractFactoryContext,\n values: Schema extends AnyZodObject ? z.output<Schema> : undefined,\n ) => Promise<Instance>,\n type: InjectableScope = InjectableScope.Singleton,\n ) {\n this.logger?.log(\n `[ServiceLocator]#registerAbstractFactory(): Registering abstract factory for ${name}`,\n )\n if (type === InjectableScope.Instance) {\n this.instanceFactories.set(token, factory)\n this.abstractFactories.delete(token)\n } else {\n this.abstractFactories.set(token, factory)\n this.instanceFactories.delete(token)\n }\n }\n\n private resolveTokenArgs<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ):\n | [\n undefined,\n Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ]\n | [FactoryTokenNotResolved | UnknownError] {\n let realArgs = args\n if (token instanceof BoundInjectionToken) {\n realArgs = token.value\n } else if (token instanceof FactoryInjectionToken) {\n if (token.resolved) {\n realArgs = token.value\n } else {\n return [new FactoryTokenNotResolved(token.name)]\n }\n }\n if (!token.schema) {\n return [undefined, realArgs]\n }\n const validatedArgs = token.schema?.safeParse(realArgs)\n if (validatedArgs && !validatedArgs.success) {\n this.logger?.error(\n `[ServiceLocator]#getInstance(): Error validating args for ${token.name.toString()}`,\n validatedArgs.error,\n )\n return [new UnknownError(validatedArgs.error)]\n }\n // @ts-expect-error We return correct type\n return [undefined, validatedArgs?.data]\n }\n\n public getInstanceIdentifier<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): string {\n const [err, realArgs] = this.resolveTokenArgs(token, args)\n if (err) {\n throw err\n }\n return this.makeInstanceName(token, realArgs)\n }\n\n public async getInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Promise<[undefined, Instance] | [UnknownError | FactoryNotFound]> {\n const [err, realArgs] = this.resolveTokenArgs(token, args)\n if (err instanceof UnknownError) {\n throw err\n } else if (\n err instanceof FactoryTokenNotResolved &&\n token instanceof FactoryInjectionToken\n ) {\n await token.resolve()\n return this.getInstance(token, args)\n }\n const instanceName = this.makeInstanceName(token, realArgs)\n const [error, holder] = this.manager.get(instanceName)\n if (!error) {\n if (holder.status === ServiceLocatorInstanceHolderStatus.Creating) {\n // @ts-expect-error TS2322 We should redefine the instance name type\n return holder.creationPromise\n } else if (\n holder.status === ServiceLocatorInstanceHolderStatus.Destroying\n ) {\n // Should never happen\n return [new UnknownError(ErrorsEnum.InstanceDestroying)]\n }\n // @ts-expect-error We should redefine the instance name type\n return [undefined, holder.instance]\n }\n switch (error.code) {\n case ErrorsEnum.InstanceDestroying:\n this.logger?.log(\n `[ServiceLocator]#getInstance() TTL expired for ${holder?.name}`,\n )\n await holder?.destroyPromise\n //Maybe we already have a new instance\n return this.getInstance<Instance, Schema>(token, args)\n\n case ErrorsEnum.InstanceExpired:\n this.logger?.log(\n `[ServiceLocator]#getInstance() TTL expired for ${holder?.name}`,\n )\n await this.invalidate(instanceName)\n //Maybe we already have a new instance\n return this.getInstance<Instance, Schema>(token, args)\n case ErrorsEnum.InstanceNotFound:\n break\n default:\n return [error]\n }\n // @ts-expect-error TS2322 It's validated\n return this.createInstance(instanceName, token, realArgs)\n }\n\n public async getOrThrowInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Promise<Instance> {\n const [error, instance] = await this.getInstance(token, args)\n if (error) {\n throw error\n }\n return instance\n }\n\n private notifyListeners(\n name: string,\n event: 'create' | 'destroy' = 'create',\n ) {\n this.logger?.log(\n `[ServiceLocator]#notifyListeners() Notifying listeners for ${name} with event ${event}`,\n )\n return this.eventBus.emit(name, event)\n }\n\n private async createInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n instanceName: string,\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Promise<[undefined, Instance] | [FactoryNotFound | UnknownError]> {\n this.logger?.log(\n `[ServiceLocator]#createInstance() Creating instance for ${instanceName}`,\n )\n let realToken =\n token instanceof BoundInjectionToken ||\n token instanceof FactoryInjectionToken\n ? token.token\n : token\n if (\n this.abstractFactories.has(realToken) ||\n this.instanceFactories.has(realToken)\n ) {\n return this.createInstanceFromAbstractFactory(\n instanceName,\n realToken,\n args,\n )\n } else {\n return [new FactoryNotFound(realToken.name.toString())]\n }\n }\n\n private async createInstanceFromAbstractFactory<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n Args extends Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n >(\n instanceName: string,\n token: InjectionToken<Instance, Schema>,\n args: Args,\n ): Promise<[undefined, Instance] | [FactoryNotFound]> {\n this.logger?.log(\n `[ServiceLocator]#createInstanceFromAbstractFactory(): Creating instance for ${instanceName} from abstract factory`,\n )\n const ctx = this.createContextForAbstractFactory(instanceName)\n let shouldStore = true\n let abstractFactory = this.abstractFactories.get(token)\n if (!abstractFactory) {\n abstractFactory = this.instanceFactories.get(token)\n shouldStore = false\n if (!abstractFactory) {\n return [new FactoryNotFound(token.name.toString())]\n }\n }\n const holder: ServiceLocatorInstanceHolder<Instance> = {\n name: instanceName,\n instance: null,\n status: ServiceLocatorInstanceHolderStatus.Creating,\n kind: ServiceLocatorInstanceHolderKind.AbstractFactory,\n // @ts-expect-error TS2322 This is correct type\n creationPromise: abstractFactory(ctx, args)\n .then(async (instance: Instance) => {\n holder.instance = instance\n holder.status = ServiceLocatorInstanceHolderStatus.Created\n holder.deps = ctx.getDependencies()\n holder.destroyListeners = ctx.getDestroyListeners()\n holder.ttl = ctx.getTtl()\n if (holder.deps.length > 0) {\n this.logger?.log(\n `[ServiceLocator]#createInstanceFromAbstractFactory(): Adding subscriptions for ${instanceName} dependencies for their invalidations: ${holder.deps.join(\n ', ',\n )}`,\n )\n holder.deps.forEach((dependency) => {\n holder.destroyListeners.push(\n this.eventBus.on(dependency, 'destroy', () =>\n this.invalidate(instanceName),\n ),\n )\n })\n }\n if (holder.ttl === 0 || !shouldStore) {\n // One time instance\n await this.invalidate(instanceName)\n }\n await this.notifyListeners(instanceName)\n return [undefined, instance as Instance]\n })\n .catch((error) => {\n this.logger?.error(\n `[ServiceLocator]#createInstanceFromAbstractFactory(): Error creating instance for ${instanceName}`,\n error,\n )\n return [new UnknownError(error)]\n }),\n effects: [],\n deps: [],\n destroyListeners: [],\n createdAt: Date.now(),\n ttl: Infinity,\n }\n\n if (shouldStore) {\n this.manager.set(instanceName, holder)\n }\n // @ts-expect-error TS2322 This is correct type\n return holder.creationPromise\n }\n\n private createContextForAbstractFactory(\n instanceName: string,\n ): ServiceLocatorAbstractFactoryContext {\n const dependencies = new Set<string>()\n const destroyListeners = new Set<() => void>()\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this\n\n function invalidate(name = instanceName) {\n return self.invalidate(name)\n }\n function addEffect(listener: () => void) {\n destroyListeners.add(listener)\n }\n let ttl = Infinity\n function setTtl(value: number) {\n ttl = value\n }\n function getTtl() {\n return ttl\n }\n\n function on(key: string, event: string, listener: (event: string) => void) {\n destroyListeners.add(self.eventBus.on(key, event, listener))\n }\n\n return {\n // @ts-expect-error This is correct type\n async inject(token, args) {\n let injectionToken = token\n if (typeof token === 'function') {\n injectionToken = getInjectableToken(token)\n }\n if (injectionToken instanceof InjectionToken) {\n const validatedArgs = token.schema\n ? token.schema.safeParse(args)\n : undefined\n const instanceName = self.makeInstanceName(token, validatedArgs)\n dependencies.add(instanceName)\n return self.getOrThrowInstance(injectionToken, args)\n }\n throw new Error(\n `[ServiceLocator]#inject(): Invalid token type: ${typeof token}. Expected a class or an InjectionToken.`,\n )\n },\n invalidate,\n eventBus: self.eventBus,\n on: on as ServiceLocatorEventBus['on'],\n getDependencies: () => Array.from(dependencies),\n addEffect,\n getDestroyListeners: () => Array.from(destroyListeners),\n setTtl,\n getTtl,\n }\n }\n\n public getSyncInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Instance | null {\n const [err, realArgs] = this.resolveTokenArgs(token, args)\n if (err) {\n return null\n }\n const instanceName = this.makeInstanceName(token, realArgs)\n const [error, holder] = this.manager.get(instanceName)\n if (error) {\n return null\n }\n return holder.instance as Instance\n }\n\n invalidate(service: string, round = 1): Promise<any> {\n this.logger?.log(\n `[ServiceLocator]#invalidate(): Starting Invalidating process of ${service}`,\n )\n const toInvalidate = this.manager.filter(\n (holder) => holder.name === service || holder.deps.includes(service),\n )\n const promises = []\n for (const [key, holder] of toInvalidate.entries()) {\n if (holder.status === ServiceLocatorInstanceHolderStatus.Destroying) {\n this.logger?.trace(\n `[ServiceLocator]#invalidate(): ${key} is already being destroyed`,\n )\n promises.push(holder.destroyPromise)\n continue\n }\n if (holder.status === ServiceLocatorInstanceHolderStatus.Creating) {\n this.logger?.trace(\n `[ServiceLocator]#invalidate(): ${key} is being created, waiting for creation to finish`,\n )\n promises.push(\n holder.creationPromise?.then(() => {\n if (round > 3) {\n this.logger?.error(\n `[ServiceLocator]#invalidate(): ${key} creation is triggering a new invalidation round, but it is still not created`,\n )\n return\n }\n return this.invalidate(key, round + 1)\n }),\n )\n continue\n }\n // @ts-expect-error TS2322 we are changing the status\n holder.status = ServiceLocatorInstanceHolderStatus.Destroying\n this.logger?.log(\n `[ServiceLocator]#invalidate(): Invalidating ${key} and notifying listeners`,\n )\n // @ts-expect-error TS2322 we are changing the status\n holder.destroyPromise = Promise.all(\n holder.destroyListeners.map((listener) => listener()),\n ).then(async () => {\n this.manager.delete(key)\n await this.notifyListeners(key, 'destroy')\n })\n promises.push(holder.destroyPromise)\n }\n return Promise.all(promises)\n }\n\n async ready() {\n return Promise.all(\n Array.from(this.manager.filter(() => true)).map(([, holder]) => {\n if (holder.status === ServiceLocatorInstanceHolderStatus.Creating) {\n return holder.creationPromise?.then(() => null)\n }\n if (holder.status === ServiceLocatorInstanceHolderStatus.Destroying) {\n return holder.destroyPromise.then(() => null)\n }\n return Promise.resolve(null)\n }),\n ).then(() => null)\n }\n\n makeInstanceName(token: InjectionToken<any, any>, args: any) {\n let stringifiedArgs = args\n ? ':' +\n JSON.stringify(args, (_, value) => {\n if (typeof value === 'function') {\n return `function:${value.name}(${value.length})`\n }\n if (typeof value === 'symbol') {\n return value.toString()\n }\n return value\n })\n .replaceAll(/\"/g, '')\n .replaceAll(/:/g, '=')\n .replaceAll(/,/g, '|')\n : ''\n const { name } = token\n if (typeof name === 'function') {\n const className = name.name\n return `${className}(${token.id})${stringifiedArgs}`\n } else if (typeof name === 'symbol') {\n return `${name.toString()}(${token.id})${stringifiedArgs}`\n } else {\n return `${name}(${token.id})${stringifiedArgs}`\n }\n }\n}\n","import { ServiceLocator } from './service-locator.mjs'\n\nlet serviceLocator: ServiceLocator = new ServiceLocator()\n\nexport function provideServiceLocator(locator: ServiceLocator): ServiceLocator {\n const original = serviceLocator\n serviceLocator = locator\n return original\n}\n\nexport function getServiceLocator(): ServiceLocator {\n if (!serviceLocator) {\n throw new Error(\n '[ServiceLocator] Service locator is not initialized. Please provide the service locator before using the @Injectable decorator.',\n )\n }\n return serviceLocator\n}\n","import { NaviosException } from '@navios/common'\n\nimport type { ClassType } from './injection-token.mjs'\nimport type { ServiceLocatorAbstractFactoryContext } from './service-locator-abstract-factory-context.mjs'\n\nimport { getServiceLocator, provideServiceLocator } from './injector.mjs'\nimport { makeProxyServiceLocator } from './proxy-service-locator.mjs'\nimport { setPromiseCollector } from './sync-injector.mjs'\n\nexport async function resolveService<T extends ClassType>(\n ctx: ServiceLocatorAbstractFactoryContext,\n target: T,\n args: any[] = [],\n): Promise<InstanceType<T>> {\n const proxyServiceLocator = makeProxyServiceLocator(getServiceLocator(), ctx)\n let promises: Promise<any>[] = []\n const promiseCollector = (promise: Promise<any>) => {\n promises.push(promise)\n }\n const originalPromiseCollector = setPromiseCollector(promiseCollector)\n const tryLoad = () => {\n const original = provideServiceLocator(proxyServiceLocator)\n let result = new target(...args)\n provideServiceLocator(original)\n return result\n }\n let instance = tryLoad()\n setPromiseCollector(originalPromiseCollector)\n if (promises.length > 0) {\n await Promise.all(promises)\n promises = []\n instance = tryLoad()\n }\n if (promises.length > 0) {\n console.error(`[ServiceLocator] ${target.name} has problem with it's definition.\n \n One or more of the dependencies are registered as a InjectableScope.Instance and are used with syncInject.\n \n Please use inject instead of syncInject to load those dependencies.`)\n throw new NaviosException(\n `[ServiceLocator] Service ${target.name} cannot be instantiated.`,\n )\n }\n\n return instance\n}\n","import type { AnyZodObject, output, z, ZodOptional } from 'zod'\n\nimport type { FactoryNotFound, UnknownError } from './index.mjs'\nimport type { InjectionToken } from './injection-token.mjs'\nimport type { ServiceLocatorAbstractFactoryContext } from './service-locator-abstract-factory-context.mjs'\nimport type { ServiceLocatorEventBus } from './service-locator-event-bus.mjs'\nimport type { ServiceLocator } from './service-locator.mjs'\n\n// @ts-expect-error We don't need all the properties of the class\nexport class ProxyServiceLocator implements ServiceLocator {\n constructor(\n private readonly serviceLocator: ServiceLocator,\n private readonly ctx: ServiceLocatorAbstractFactoryContext,\n ) {}\n get abstractFactories(): Map<\n InjectionToken<any, any>,\n (ctx: ServiceLocatorAbstractFactoryContext, args: any) => Promise<any>\n > {\n return this.serviceLocator['abstractFactories']\n }\n getEventBus(): ServiceLocatorEventBus {\n return this.serviceLocator.getEventBus()\n }\n public registerAbstractFactory<\n Instance,\n Schema extends AnyZodObject | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n factory: (\n ctx: ServiceLocatorAbstractFactoryContext,\n values: Schema extends AnyZodObject ? output<Schema> : undefined,\n ) => Promise<Instance>,\n ): void {\n return this.serviceLocator.registerAbstractFactory(token, factory)\n }\n public getInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Promise<[undefined, Instance] | [UnknownError | FactoryNotFound]> {\n return this.ctx.inject(token, args).then(\n (instance) => {\n return [undefined, instance]\n },\n (error) => {\n return [error]\n },\n )\n }\n public getOrThrowInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Promise<Instance> {\n return this.ctx.inject(token, args)\n }\n public getSyncInstance<\n Instance,\n Schema extends AnyZodObject | ZodOptional<AnyZodObject> | undefined,\n >(\n token: InjectionToken<Instance, Schema>,\n args: Schema extends AnyZodObject\n ? z.input<Schema>\n : Schema extends ZodOptional<AnyZodObject>\n ? z.input<Schema> | undefined\n : undefined,\n ): Instance | null {\n return this.serviceLocator.getSyncInstance(token, args)\n }\n invalidate(service: string, round?: number): Promise<any> {\n return this.serviceLocator.invalidate(service, round)\n }\n ready(): Promise<null> {\n return this.serviceLocator.ready()\n }\n makeInstanceName(token: InjectionToken<any, any>, args: any): string {\n return this.serviceLocator.makeInstanceName(token, args)\n }\n}\n\nexport function makeProxyServiceLocator(\n serviceLocator: ServiceLocator,\n ctx: ServiceLocatorAbstractFactoryContext,\n): ServiceLocator {\n // @ts-expect-error We don't need all the properties of the class\n return new ProxyServiceLocator(serviceLocator, ctx)\n}\n","import type { AnyZodObject, z, ZodOptional } from 'zod'\n\nimport type { ClassType } from './injection-token.mjs'\n\nimport { getInjectableToken } from './decorators/index.mjs'\nimport { InjectionToken } from './injection-token.mjs'\nimport { getServiceLocator } from './injector.mjs'\n\nlet promiseCollector: null | ((promise: Promise<any>) => void) = null\n\nexport function syncInject<T extends ClassType>(token: T): InstanceType<T>\nexport function syncInject<T, S extends AnyZodObject>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): T\nexport function syncInject<T, S extends ZodOptional<AnyZodObject>>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): T\n\nexport function syncInject<T>(token: InjectionToken<T, undefined>): T\nexport function syncInject<\n T,\n Token extends InjectionToken<T>,\n S extends AnyZodObject | unknown = Token['schema'],\n>(token: Token, args?: S extends AnyZodObject ? z.input<S> : never): T {\n let realToken: InjectionToken<T, S> = token\n if (!(token instanceof InjectionToken)) {\n realToken = getInjectableToken(token) as InjectionToken<T, S>\n }\n\n const instance = getServiceLocator().getSyncInstance(realToken, args)\n if (!instance) {\n if (promiseCollector) {\n const promise = getServiceLocator().getInstance(realToken, args)\n promiseCollector(promise)\n } else {\n throw new Error(\n `[ServiceLocator] No instance found for ${realToken.name.toString()}`,\n )\n }\n }\n return instance as unknown as T\n}\n\nexport function setPromiseCollector(\n collector: null | ((promise: Promise<any>) => void),\n): typeof promiseCollector {\n const original = promiseCollector\n promiseCollector = collector\n return original\n}\n","import type { ClassType, InjectionToken } from '../injection-token.mjs'\n\nimport { InjectableTokenMeta } from './injectable.decorator.mjs'\n\nexport function getInjectableToken<R>(\n target: ClassType,\n): R extends { create(...args: any[]): infer V }\n ? InjectionToken<V>\n : InjectionToken<R> {\n // @ts-expect-error We inject the token into the class itself\n const token = target[InjectableTokenMeta] as InjectionToken<any, any>\n if (!token) {\n throw new Error(\n `[ServiceLocator] Class ${target.name} is not decorated with @Injectable.`,\n )\n }\n // @ts-expect-error We detect factory or class\n return token\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable @typescript-eslint/no-empty-object-type */\n/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type EventsConfig = {\n [event: string]: any[]\n}\nexport type EventsNames<Events extends EventsConfig> = Exclude<keyof Events, symbol | number>\nexport type EventsArgs<\n Events extends EventsConfig,\n Name extends EventsNames<Events>,\n> = Events[Name] extends any[] ? Events[Name] : []\n\nexport type ChannelEmitter<\n Events extends EventsConfig,\n Ns extends string,\n E extends EventsNames<Events>,\n> = {\n emit<Args extends EventsArgs<Events, E>>(ns: Ns, event: E, ...args: Args): Promise<any>\n}\n\nexport interface EventEmitterInterface<Events extends EventsConfig> {\n on<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(\n event: E,\n listener: (...args: Args) => void,\n ): () => void\n emit<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(\n event: E,\n ...args: Args\n ): void\n addChannel<\n E extends EventsNames<Events>,\n Ns extends string,\n Emmiter extends ChannelEmitter<Events, Ns, E>,\n >(\n ns: Ns,\n event: E,\n target: Emmiter,\n ): () => void\n}\n\nexport class EventEmitter<Events extends EventsConfig = {}>\n implements EventEmitterInterface<Events>\n{\n private listeners: Map<EventsNames<Events>, Set<Function>> = new Map()\n\n on<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(\n event: E,\n listener: (...args: Args) => void,\n ) {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set())\n }\n\n this.listeners.get(event)!.add(listener)\n\n return () => {\n this.off(event, listener)\n }\n }\n\n off<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(\n event: E,\n listener: (...args: Args) => void,\n ) {\n if (!this.listeners.has(event)) {\n return\n }\n\n this.listeners.get(event)!.delete(listener)\n if (this.listeners.get(event)!.size === 0) {\n this.listeners.delete(event)\n }\n }\n\n once<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(\n event: E,\n listener: (...args: Args) => void,\n ) {\n const off = this.on(event, (...args) => {\n off()\n // @ts-expect-error - This is a valid call\n listener(...args)\n })\n\n return off\n }\n\n async emit<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(\n event: E,\n ...args: Args\n ): Promise<any> {\n if (!this.listeners.has(event)) {\n return\n }\n\n return Promise.all(Array.from(this.listeners.get(event)!).map(listener => listener(...args)))\n }\n\n addChannel<\n E extends EventsNames<Events>,\n Ns extends string,\n Emitter extends ChannelEmitter<Events, Ns, E>,\n >(ns: Ns, event: E, target: Emitter) {\n return this.on(event, (...args) => target.emit(ns, event, ...args))\n }\n}\n","import type { AnyZodObject, z, ZodOptional } from 'zod'\n\nimport type { ClassType } from './injection-token.mjs'\n\nimport { getInjectableToken } from './decorators/index.mjs'\nimport { InjectionToken } from './injection-token.mjs'\nimport { getServiceLocator } from './injector.mjs'\n\nexport function inject<T extends ClassType>(token: T): Promise<InstanceType<T>>\nexport function inject<T, S extends AnyZodObject>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): Promise<T>\nexport function inject<T, S extends ZodOptional<AnyZodObject>>(\n token: InjectionToken<T, S>,\n args?: z.input<S>,\n): Promise<T>\n\nexport function inject<T>(token: InjectionToken<T, undefined>): Promise<T>\nexport function inject(token: InjectionToken<any>, args?: unknown) {\n let realToken = token\n if (!(token instanceof InjectionToken)) {\n realToken = getInjectableToken(token)\n }\n\n // @ts-expect-error We chek the type in overload\n return getServiceLocator().getOrThrowInstance(realToken, args)\n}\n","import type { ClassType, InjectionToken } from './injection-token.mjs'\n\nimport { getServiceLocator } from './injector.mjs'\n\n/**\n * Useful for tests or when you want to override a service\n * with a different implementation.\n */\nexport function override<T>(token: InjectionToken<T>, target: ClassType) {\n const serviceLocator = getServiceLocator()\n const originalDefinition = serviceLocator['abstractFactories'].get(token)\n serviceLocator.registerAbstractFactory(token, async (ctx, args: any) => {\n const builder = new target()\n return builder.create(ctx, args)\n })\n\n return () => {\n if (originalDefinition) {\n serviceLocator.registerAbstractFactory(token, originalDefinition)\n }\n }\n}\n","import { z } from 'zod'\n\nimport {\n Injectable,\n InjectableType,\n InjectionToken,\n} from '../service-locator/index.mjs'\nimport { LoggerInstance } from './logger.service.mjs'\n\nexport const LoggerInjectionToken = 'LoggerInjectionToken'\n\nexport const LoggerOptions = z\n .object({\n context: z.string().optional(),\n options: z\n .object({\n timestamp: z.boolean().optional(),\n })\n .optional(),\n })\n .optional()\n\nexport const Logger = InjectionToken.create<\n LoggerInstance,\n typeof LoggerOptions\n>(LoggerInjectionToken, LoggerOptions)\n\n@Injectable({\n type: InjectableType.Factory,\n token: Logger,\n})\nexport class LoggerFactory {\n create(ctx: any, args: z.infer<typeof LoggerOptions>) {\n // @ts-expect-error We don't need to support this in the current version\n return new LoggerInstance(args?.context, args?.options)\n }\n}\n","import type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-service.interface.mjs'\n\nimport { Injectable } from '../service-locator/index.mjs'\nimport { ConsoleLogger } from './console-logger.service.mjs'\nimport { isLogLevelEnabled, isObject } from './utils/index.mjs'\n\nconst DEFAULT_LOGGER = new ConsoleLogger()\n\nconst dateTimeFormatter = new Intl.DateTimeFormat(undefined, {\n year: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n day: '2-digit',\n month: '2-digit',\n})\n\n// @ts-expect-error We don't need to support this in the current version\n@Injectable()\nexport class LoggerInstance implements LoggerService {\n protected static staticInstanceRef?: LoggerService = DEFAULT_LOGGER\n protected static logLevels?: LogLevel[]\n\n protected localInstanceRef?: LoggerService\n\n constructor()\n constructor(context: string)\n constructor(context: string, options?: { timestamp?: boolean })\n constructor(\n protected context?: string,\n protected options: { timestamp?: boolean } = {},\n ) {}\n\n get localInstance(): LoggerService {\n if (LoggerInstance.staticInstanceRef === DEFAULT_LOGGER) {\n return this.registerLocalInstanceRef()\n } else if (LoggerInstance.staticInstanceRef instanceof LoggerInstance) {\n const prototype = Object.getPrototypeOf(LoggerInstance.staticInstanceRef)\n if (prototype.constructor === LoggerInstance) {\n return this.registerLocalInstanceRef()\n }\n }\n return LoggerInstance.staticInstanceRef!\n }\n\n /**\n * Write an 'error' level log.\n */\n error(message: any, stack?: string, context?: string): void\n error(message: any, ...optionalParams: [...any, string?, string?]): void\n error(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? (optionalParams.length ? optionalParams : [undefined]).concat(\n this.context,\n )\n : optionalParams\n\n this.localInstance?.error(message, ...optionalParams)\n }\n\n /**\n * Write a 'log' level log.\n */\n log(message: any, context?: string): void\n log(message: any, ...optionalParams: [...any, string?]): void\n log(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? optionalParams.concat(this.context)\n : optionalParams\n this.localInstance?.log(message, ...optionalParams)\n }\n\n /**\n * Write a 'warn' level log.\n */\n warn(message: any, context?: string): void\n warn(message: any, ...optionalParams: [...any, string?]): void\n warn(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? optionalParams.concat(this.context)\n : optionalParams\n this.localInstance?.warn(message, ...optionalParams)\n }\n\n /**\n * Write a 'debug' level log.\n */\n debug(message: any, context?: string): void\n debug(message: any, ...optionalParams: [...any, string?]): void\n debug(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? optionalParams.concat(this.context)\n : optionalParams\n this.localInstance?.debug?.(message, ...optionalParams)\n }\n\n /**\n * Write a 'verbose' level log.\n */\n verbose(message: any, context?: string): void\n verbose(message: any, ...optionalParams: [...any, string?]): void\n verbose(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? optionalParams.concat(this.context)\n : optionalParams\n this.localInstance?.verbose?.(message, ...optionalParams)\n }\n\n /**\n * Write a 'fatal' level log.\n */\n fatal(message: any, context?: string): void\n fatal(message: any, ...optionalParams: [...any, string?]): void\n fatal(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? optionalParams.concat(this.context)\n : optionalParams\n this.localInstance?.fatal?.(message, ...optionalParams)\n }\n\n /**\n * Write an 'error' level log.\n */\n static error(message: any, stackOrContext?: string): void\n static error(message: any, context?: string): void\n static error(message: any, stack?: string, context?: string): void\n static error(\n message: any,\n ...optionalParams: [...any, string?, string?]\n ): void\n static error(message: any, ...optionalParams: any[]) {\n this.staticInstanceRef?.error(message, ...optionalParams)\n }\n\n /**\n * Write a 'log' level log.\n */\n static log(message: any, context?: string): void\n static log(message: any, ...optionalParams: [...any, string?]): void\n static log(message: any, ...optionalParams: any[]) {\n this.staticInstanceRef?.log(message, ...optionalParams)\n }\n\n /**\n * Write a 'warn' level log.\n */\n static warn(message: any, context?: string): void\n static warn(message: any, ...optionalParams: [...any, string?]): void\n static warn(message: any, ...optionalParams: any[]) {\n this.staticInstanceRef?.warn(message, ...optionalParams)\n }\n\n /**\n * Write a 'debug' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n static debug(message: any, context?: string): void\n static debug(message: any, ...optionalParams: [...any, string?]): void\n static debug(message: any, ...optionalParams: any[]) {\n this.staticInstanceRef?.debug?.(message, ...optionalParams)\n }\n\n /**\n * Write a 'verbose' level log.\n */\n static verbose(message: any, context?: string): void\n static verbose(message: any, ...optionalParams: [...any, string?]): void\n static verbose(message: any, ...optionalParams: any[]) {\n this.staticInstanceRef?.verbose?.(message, ...optionalParams)\n }\n\n /**\n * Write a 'fatal' level log.\n */\n static fatal(message: any, context?: string): void\n static fatal(message: any, ...optionalParams: [...any, string?]): void\n static fatal(message: any, ...optionalParams: any[]) {\n this.staticInstanceRef?.fatal?.(message, ...optionalParams)\n }\n\n static getTimestamp() {\n return dateTimeFormatter.format(Date.now())\n }\n\n static overrideLogger(logger: LoggerService | LogLevel[] | boolean) {\n if (Array.isArray(logger)) {\n LoggerInstance.logLevels = logger\n return this.staticInstanceRef?.setLogLevels?.(logger)\n }\n if (isObject(logger)) {\n this.staticInstanceRef = logger as LoggerService\n } else {\n this.staticInstanceRef = undefined\n }\n }\n\n static isLevelEnabled(level: LogLevel): boolean {\n const logLevels = LoggerInstance.logLevels\n return isLogLevelEnabled(level, logLevels)\n }\n\n private registerLocalInstanceRef() {\n if (this.localInstanceRef) {\n return this.localInstanceRef\n }\n this.localInstanceRef = new ConsoleLogger(this.context!, {\n timestamp: this.options?.timestamp,\n logLevels: LoggerInstance.logLevels,\n })\n return this.localInstanceRef\n }\n}\n","import type { LoggerService } from './logger-service.interface.mjs'\n\nimport { LoggerInstance } from './logger.service.mjs'\n\nexport class PinoWrapper {\n constructor(protected readonly logger: LoggerService) {}\n\n fatal(message: any, ...optionalParams: any[]) {\n if (this.logger.fatal === undefined) {\n return this.error(message, ...optionalParams)\n }\n this.logger.fatal(message, ...optionalParams)\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.logger.error(message, ...optionalParams)\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.logger.warn(message, ...optionalParams)\n }\n\n info() {\n // We don't want to populate the logs with the original fastify logs\n // this.logger.debug?.('INFO', message, ...optionalParams)\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.logger.debug?.(message, ...optionalParams)\n }\n\n trace(message: any, ...optionalParams: any[]) {\n this.logger.verbose?.(message, ...optionalParams)\n }\n\n silent() {\n // noop\n }\n\n child(options: any) {\n const keys = Object.keys(options)\n // @ts-expect-error We don't need to support this in the current version\n let newContext = this.logger['context'] ?? ''\n if (keys.length > 1) {\n // @ts-expect-error We don't need to support this in the current version\n newContext = `${this.logger['context'] ?? ''}:${JSON.stringify(options)}`\n }\n return new PinoWrapper(\n // @ts-expect-error We don't need to support this in the current version\n new LoggerInstance(newContext, this.logger['options']),\n )\n }\n\n get level(): any {\n if ('level' in this.logger && this.logger.level) {\n return this.logger.level\n }\n const levels = LoggerInstance['logLevels']\n if (levels) {\n return levels.find((level) => level !== 'verbose')\n }\n return 'warn'\n }\n}\n","import { NaviosException } from '@navios/common'\n\nimport type { LoggerService } from '../logger/index.mjs'\nimport type { ConfigService } from './config-service.interface.mjs'\nimport type { Path, PathValue } from './types.mjs'\n\nexport class ConfigServiceInstance<Config = Record<string, unknown>>\n implements ConfigService<Config>\n{\n constructor(\n private config: Config = {} as Config,\n private logger: LoggerService,\n ) {}\n\n getConfig(): Config {\n return this.config\n }\n\n get<Key extends Path<Config>>(key: Key): PathValue<Config, Key> | null {\n try {\n const parts = String(key).split('.')\n let value: any = this.config\n\n for (const part of parts) {\n if (\n value === null ||\n value === undefined ||\n typeof value !== 'object'\n ) {\n return null\n }\n value = value[part]\n }\n\n return (value as PathValue<Config, Key>) ?? null\n } catch (error) {\n this.logger.debug?.(\n `Failed to get config value for key ${String(key)}`,\n error,\n )\n return null\n }\n }\n\n getOrDefault<Key extends Path<Config>>(\n key: Key,\n defaultValue: PathValue<Config, Key>,\n ): PathValue<Config, Key> {\n const value = this.get(key)\n return value !== null ? value : defaultValue\n }\n\n getOrThrow<Key extends Path<Config>>(\n key: Key,\n errorMessage?: string,\n ): PathValue<Config, Key> {\n const value = this.get(key)\n\n if (value === null) {\n const message =\n errorMessage ||\n `Configuration value for key \"${String(key)}\" is not defined`\n this.logger.error(message)\n throw new NaviosException(message)\n }\n\n return value\n }\n}\n","import type { BaseEndpointConfig, HttpMethod } from '@navios/common'\nimport type { HttpHeader } from 'fastify/types/utils.js'\n\nimport type { CanActivate } from '../interfaces/index.mjs'\nimport type {\n ClassTypeWithInstance,\n InjectionToken,\n} from '../service-locator/index.mjs'\n\nexport const EndpointMetadataKey = Symbol('EndpointMetadataKey')\n\nexport enum EndpointType {\n Unknown = 'unknown',\n Config = 'config',\n Handler = 'handler',\n}\n\nexport interface EndpointMetadata {\n classMethod: string\n url: string\n successStatusCode: number\n type: EndpointType\n headers: Partial<Record<HttpHeader, number | string | string[] | undefined>>\n httpMethod: HttpMethod\n config: BaseEndpointConfig | null\n guards: Set<\n ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>\n >\n customAttributes: Map<string | symbol, any>\n}\n\nexport function getAllEndpointMetadata(\n context: ClassMethodDecoratorContext | ClassDecoratorContext,\n): Set<EndpointMetadata> {\n if (context.metadata) {\n const metadata = context.metadata[EndpointMetadataKey] as\n | Set<EndpointMetadata>\n | undefined\n if (metadata) {\n return metadata\n } else {\n context.metadata[EndpointMetadataKey] = new Set<EndpointMetadata>()\n return context.metadata[EndpointMetadataKey] as Set<EndpointMetadata>\n }\n }\n throw new Error('[Navios] Wrong environment.')\n}\n\nexport function getEndpointMetadata(\n target: Function,\n context: ClassMethodDecoratorContext,\n): EndpointMetadata {\n if (context.metadata) {\n const metadata = getAllEndpointMetadata(context)\n if (metadata) {\n const endpointMetadata = Array.from(metadata).find(\n (item) => item.classMethod === target.name,\n )\n if (endpointMetadata) {\n return endpointMetadata\n } else {\n const newMetadata: EndpointMetadata = {\n classMethod: target.name,\n url: '',\n successStatusCode: 200,\n headers: {},\n type: EndpointType.Unknown,\n httpMethod: 'GET',\n config: null,\n guards: new Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >(),\n customAttributes: new Map<string | symbol, any>(),\n }\n metadata.add(newMetadata)\n return newMetadata\n }\n }\n }\n throw new Error('[Navios] Wrong environment.')\n}\n","import type { CanActivate } from '../interfaces/index.mjs'\nimport type {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '../service-locator/index.mjs'\nimport type { EndpointMetadata } from './endpoint.metadata.mjs'\n\nimport { getAllEndpointMetadata } from './endpoint.metadata.mjs'\n\nexport const ControllerMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ControllerMetadata {\n endpoints: Set<EndpointMetadata>\n guards: Set<\n ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>\n >\n customAttributes: Map<string | symbol, any>\n}\n\nexport function getControllerMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): ControllerMetadata {\n if (context.metadata) {\n const metadata = context.metadata[ControllerMetadataKey] as\n | ControllerMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const endpointsMetadata = getAllEndpointMetadata(context)\n const newMetadata: ControllerMetadata = {\n endpoints: endpointsMetadata,\n guards: new Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >(),\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[ControllerMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[ControllerMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios] Wrong environment.')\n}\n\nexport function extractControllerMetadata(\n target: ClassType,\n): ControllerMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ControllerMetadataKey] as\n | ControllerMetadata\n | undefined\n if (!metadata) {\n throw new Error(\n '[Navios] Controller metadata not found. Make sure to use @Controller decorator.',\n )\n }\n return metadata\n}\n\nexport function hasControllerMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ControllerMetadataKey] as\n | ControllerMetadata\n | undefined\n return !!metadata\n}\n","import type { CanActivate } from '../index.mjs'\nimport type {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '../service-locator/index.mjs'\n\nexport const ModuleMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ModuleMetadata {\n controllers: Set<ClassType>\n imports: Set<ClassType>\n guards: Set<\n ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>\n >\n customAttributes: Map<string | symbol, any>\n}\n\nexport function getModuleMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): ModuleMetadata {\n if (context.metadata) {\n const metadata = context.metadata[ModuleMetadataKey] as\n | ModuleMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const newMetadata: ModuleMetadata = {\n controllers: new Set<ClassType>(),\n imports: new Set<ClassType>(),\n guards: new Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >(),\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[ModuleMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[ModuleMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios] Wrong environment.')\n}\n\nexport function extractModuleMetadata(target: ClassType): ModuleMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ModuleMetadataKey] as ModuleMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios] Module metadata not found. Make sure to use @Module decorator.',\n )\n }\n return metadata\n}\n\nexport function hasModuleMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n return !!target[ModuleMetadataKey]\n}\n","import type { ClassType } from '../service-locator/index.mjs'\n\nimport { getControllerMetadata } from '../metadata/index.mjs'\nimport {\n Injectable,\n InjectableScope,\n InjectableType,\n InjectionToken,\n} from '../service-locator/index.mjs'\n\nexport interface ControllerOptions {\n guards?: ClassType[] | Set<ClassType>\n}\nexport function Controller({ guards }: ControllerOptions = {}) {\n return function (target: ClassType, context: ClassDecoratorContext) {\n if (context.kind !== 'class') {\n throw new Error(\n '[Navios] @Controller decorator can only be used on classes.',\n )\n }\n const token = InjectionToken.create(target)\n if (context.metadata) {\n const controllerMetadata = getControllerMetadata(target, context)\n if (guards) {\n for (const guard of Array.from(guards).reverse()) {\n controllerMetadata.guards.add(guard)\n }\n }\n }\n return Injectable({\n token,\n type: InjectableType.Class,\n scope: InjectableScope.Instance,\n })(target, context)\n }\n}\n","import type {\n BaseEndpointConfig,\n EndpointFunctionArgs,\n HttpMethod,\n} from '@navios/common'\nimport type { AnyZodObject, z, ZodType } from 'zod'\n\nimport { EndpointType, getEndpointMetadata } from '../metadata/index.mjs'\n\nexport type EndpointParams<\n EndpointDeclaration extends {\n config: BaseEndpointConfig<any, any, any, any, any>\n },\n Url extends string = EndpointDeclaration['config']['url'],\n QuerySchema = EndpointDeclaration['config']['querySchema'],\n> = QuerySchema extends AnyZodObject\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema']\n >\n : EndpointFunctionArgs<Url, QuerySchema, undefined>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema']\n >\n : EndpointFunctionArgs<Url, undefined, undefined>\n\nexport function Endpoint<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n ResponseSchema extends ZodType = ZodType,\n RequestSchema = ZodType,\n>(endpoint: {\n config: BaseEndpointConfig<\n Method,\n Url,\n QuerySchema,\n ResponseSchema,\n RequestSchema\n >\n}) {\n return (\n target: (\n params: QuerySchema extends AnyZodObject\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema>\n : EndpointFunctionArgs<Url, QuerySchema, undefined>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema>\n : EndpointFunctionArgs<Url, undefined, undefined>,\n ) => z.input<ResponseSchema>,\n context: ClassMethodDecoratorContext,\n ) => {\n if (typeof target !== 'function') {\n throw new Error(\n '[Navios] Endpoint decorator can only be used on functions.',\n )\n }\n if (context.kind !== 'method') {\n throw new Error(\n '[Navios] Endpoint decorator can only be used on methods.',\n )\n }\n const config = endpoint.config\n if (context.metadata) {\n let endpointMetadata = getEndpointMetadata(target, context)\n if (endpointMetadata.config && endpointMetadata.config.url) {\n throw new Error(\n `[Navios] Endpoint ${config.method} ${config.url} already exists. Please use a different method or url.`,\n )\n }\n // @ts-expect-error We don't need to set correctly in the metadata\n endpointMetadata.config = config\n endpointMetadata.type = EndpointType.Config\n endpointMetadata.classMethod = target.name\n endpointMetadata.httpMethod = config.method\n endpointMetadata.url = config.url\n }\n return target\n }\n}\n","import type { HttpHeader } from 'fastify/types/utils.js'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\n\nexport function Header(name: HttpHeader, value: string | number | string[]) {\n return <T extends Function>(\n target: T,\n context: ClassMethodDecoratorContext,\n ) => {\n if (context.kind !== 'method') {\n throw new Error('[Navios] Header decorator can only be used on methods.')\n }\n const metadata = getEndpointMetadata(target, context)\n metadata.headers[name] = value\n\n return target\n }\n}\n","import { getEndpointMetadata } from '../metadata/index.mjs'\n\nexport function HttpCode(code: number) {\n return <T extends Function>(\n target: T,\n context: ClassMethodDecoratorContext,\n ) => {\n if (context.kind !== 'method') {\n throw new Error(\n '[Navios] HttpCode decorator can only be used on methods.',\n )\n }\n const metadata = getEndpointMetadata(target, context)\n metadata.successStatusCode = code\n\n return target\n }\n}\n","import type { ClassType } from '../service-locator/index.mjs'\n\nimport { getModuleMetadata } from '../metadata/index.mjs'\nimport {\n Injectable,\n InjectableScope,\n InjectableType,\n InjectionToken,\n} from '../service-locator/index.mjs'\n\nexport interface ModuleOptions {\n controllers?: ClassType[] | Set<ClassType>\n imports?: ClassType[] | Set<ClassType>\n guards?: ClassType[] | Set<ClassType>\n}\n\nexport function Module(metadata: ModuleOptions) {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error('[Navios] @Module decorator can only be used on classes.')\n }\n // Register the module in the service locator\n const token = InjectionToken.create(target)\n const moduleMetadata = getModuleMetadata(target, context)\n if (metadata.controllers) {\n for (const controller of metadata.controllers) {\n moduleMetadata.controllers.add(controller)\n }\n }\n if (metadata.imports) {\n for (const importedModule of metadata.imports) {\n moduleMetadata.imports.add(importedModule)\n }\n }\n if (metadata.guards) {\n for (const guard of Array.from(metadata.guards).reverse()) {\n moduleMetadata.guards.add(guard)\n }\n }\n\n return Injectable({\n token,\n type: InjectableType.Class,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","import type { CanActivate } from '../interfaces/index.mjs'\nimport type {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '../service-locator/index.mjs'\n\nimport {\n getControllerMetadata,\n getEndpointMetadata,\n} from '../metadata/index.mjs'\n\nexport function UseGuards(\n ...guards: (\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n )[]\n) {\n return function <T extends Function>(\n target: T,\n context: ClassMethodDecoratorContext | ClassDecoratorContext,\n ): T {\n if (context.kind === 'class') {\n const controllerMetadata = getControllerMetadata(\n target as unknown as ClassType,\n context,\n )\n for (const guard of guards.reverse()) {\n controllerMetadata.guards.add(guard)\n }\n } else if (context.kind === 'method') {\n const endpointMetadata = getEndpointMetadata(target, context)\n for (const guard of guards.reverse()) {\n endpointMetadata.guards.add(guard)\n }\n } else {\n throw new Error(\n '[Navios] @UseGuards decorator can only be used on classes or methods.',\n )\n }\n return target\n }\n}\n","export class HttpException {\n constructor(\n public readonly statusCode: number,\n public readonly response: string | object,\n public readonly error?: Error,\n ) {}\n}\n","import { HttpException } from './http.exception.mjs'\n\nexport class BadRequestException extends HttpException {\n constructor(message: string | object) {\n super(400, message)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\nexport class ForbiddenException extends HttpException {\n constructor(message: string) {\n super(403, message)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\nexport class InternalServerErrorException extends HttpException {\n constructor(message: string | object, error?: Error) {\n super(500, message, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\nexport class NotFoundException extends HttpException {\n constructor(\n public readonly response: string | object,\n public readonly error?: Error,\n ) {\n super(404, response, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\nexport class UnauthorizedException extends HttpException {\n constructor(message: string | object, error?: Error) {\n super(401, message, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\nexport class ConflictException extends HttpException {\n constructor(message: string | object, error?: Error) {\n super(409, message, error)\n }\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\nimport type { ZodTypeProvider } from 'fastify-type-provider-zod'\n\nimport { NaviosException } from '@navios/common'\n\nimport type { EndpointMetadata, ModuleMetadata } from '../metadata/index.mjs'\nimport type { ClassType } from '../service-locator/index.mjs'\n\nimport { Logger } from '../logger/index.mjs'\nimport { EndpointType, extractControllerMetadata } from '../metadata/index.mjs'\nimport {\n getServiceLocator,\n inject,\n Injectable,\n syncInject,\n} from '../service-locator/index.mjs'\nimport { ExecutionContextToken, Reply, Request } from '../tokens/index.mjs'\nimport { ExecutionContext } from './execution-context.mjs'\nimport { GuardRunnerService } from './guard-runner.service.mjs'\n\n@Injectable()\nexport class ControllerAdapterService {\n guardRunner = syncInject(GuardRunnerService)\n private logger = syncInject(Logger, {\n context: ControllerAdapterService.name,\n })\n\n setupController(\n controller: ClassType,\n instance: FastifyInstance,\n moduleMetadata: ModuleMetadata,\n ): void {\n const controllerMetadata = extractControllerMetadata(controller)\n for (const endpoint of controllerMetadata.endpoints) {\n const { classMethod, url, httpMethod } = endpoint\n\n if (!url) {\n throw new Error(\n `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`,\n )\n }\n const executionContext = new ExecutionContext(\n moduleMetadata,\n controllerMetadata,\n endpoint,\n )\n instance.withTypeProvider<ZodTypeProvider>().route({\n method: httpMethod,\n url: url.replaceAll('$', ':'),\n schema: this.provideSchemaForConfig(endpoint),\n preHandler: this.providePreHandler(executionContext),\n handler: this.provideHandler(controller, executionContext, endpoint),\n })\n\n this.logger.debug(\n `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`,\n )\n }\n }\n\n providePreHandler(executionContext: ExecutionContext) {\n const guards = this.guardRunner.makeContext(executionContext)\n return guards.size > 0\n ? async (request: FastifyRequest, reply: FastifyReply) => {\n getServiceLocator().registerInstance(Request, request)\n getServiceLocator().registerInstance(Reply, reply)\n getServiceLocator().registerInstance(\n ExecutionContextToken,\n executionContext,\n )\n executionContext.provideRequest(request)\n executionContext.provideReply(reply)\n let canActivate = true\n try {\n canActivate = await this.guardRunner.runGuards(\n guards,\n executionContext,\n )\n } finally {\n getServiceLocator().removeInstance(Request)\n getServiceLocator().removeInstance(Reply)\n getServiceLocator().removeInstance(ExecutionContextToken)\n }\n if (!canActivate) {\n return reply\n }\n }\n : undefined\n }\n\n private provideSchemaForConfig(endpointMetadata: EndpointMetadata) {\n if (!endpointMetadata.config) {\n this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`)\n return {}\n }\n const { querySchema, requestSchema, responseSchema } =\n endpointMetadata.config\n const schema: Record<string, any> = {}\n if (querySchema) {\n schema.querystring = querySchema\n }\n if (requestSchema) {\n schema.body = requestSchema\n }\n if (responseSchema) {\n schema.response = {\n 200: responseSchema,\n }\n }\n\n return schema\n }\n\n private provideHandler(\n controller: ClassType,\n executionContext: ExecutionContext,\n endpointMetadata: EndpointMetadata,\n ): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n switch (endpointMetadata.type) {\n case EndpointType.Unknown:\n this.logger.error(\n `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`,\n )\n throw new NaviosException('Unknown endpoint type')\n case EndpointType.Config:\n return this.provideHandlerForConfig(\n controller,\n executionContext,\n endpointMetadata,\n )\n case EndpointType.Handler:\n this.logger.error('Not implemented yet')\n throw new NaviosException('Not implemented yet')\n }\n }\n\n private provideHandlerForConfig(\n controller: ClassType,\n executionContext: ExecutionContext,\n endpointMetadata: EndpointMetadata,\n ): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n return async (request, reply) => {\n getServiceLocator().registerInstance(Request, request)\n getServiceLocator().registerInstance(Reply, reply)\n getServiceLocator().registerInstance(\n ExecutionContextToken,\n executionContext,\n )\n executionContext.provideRequest(request)\n executionContext.provideReply(reply)\n const controllerInstance = await inject(controller)\n try {\n const { query, params, body } = request\n const argument: Record<string, any> = {}\n if (query && Object.keys(query).length > 0) {\n argument.params = query\n }\n if (params && Object.keys(params).length > 0) {\n argument.urlParams = params\n }\n if (body) {\n argument.data = body\n }\n const result =\n await controllerInstance[endpointMetadata.classMethod](argument)\n reply\n .status(endpointMetadata.successStatusCode)\n .headers(endpointMetadata.headers)\n .send(result)\n } finally {\n getServiceLocator().removeInstance(Request)\n getServiceLocator().removeInstance(Reply)\n getServiceLocator().removeInstance(ExecutionContextToken)\n }\n }\n }\n}\n","import type { FastifyInstance } from 'fastify'\n\nimport { InjectionToken } from '../service-locator/index.mjs'\n\nconst ApplicationInjectionToken = 'ApplicationInjectionToken'\n\nexport const Application = InjectionToken.create<FastifyInstance>(\n ApplicationInjectionToken,\n)\n","import { InjectionToken } from '../service-locator/index.mjs'\nimport { ExecutionContext } from '../services/index.mjs'\n\nexport const ExecutionContextInjectionToken = 'ExecutionContextInjectionToken'\n\nexport const ExecutionContextToken = InjectionToken.create<ExecutionContext>(\n ExecutionContextInjectionToken,\n)\n","import type { FastifyReply } from 'fastify'\n\nimport { InjectionToken } from '../service-locator/index.mjs'\n\nconst ReplyInjectionToken = 'ReplyInjectionToken'\n\nexport const Reply = InjectionToken.create<FastifyReply>(ReplyInjectionToken)\n","import type { FastifyRequest } from 'fastify'\n\nimport { InjectionToken } from '../service-locator/index.mjs'\n\nconst RequestInjectionToken = 'RequestInjectionToken'\n\nexport const Request = InjectionToken.create<FastifyRequest>(\n RequestInjectionToken,\n)\n","import type { FastifyReply, FastifyRequest } from 'fastify'\n\nimport type {\n ControllerMetadata,\n EndpointMetadata,\n ModuleMetadata,\n} from '../metadata/index.mjs'\n\nexport class ExecutionContext {\n private request: FastifyRequest | undefined\n private reply: FastifyReply | undefined\n constructor(\n private readonly module: ModuleMetadata,\n private readonly controller: ControllerMetadata,\n private readonly handler: EndpointMetadata,\n ) {}\n getModule(): ModuleMetadata {\n return this.module\n }\n\n getController(): ControllerMetadata {\n return this.controller\n }\n\n getHandler(): EndpointMetadata {\n return this.handler\n }\n\n getRequest(): FastifyRequest {\n if (!this.request) {\n throw new Error(\n '[Navios] Request is not set. Make sure to set it before using it.',\n )\n }\n return this.request\n }\n\n getReply(): FastifyReply {\n if (!this.reply) {\n throw new Error(\n '[Navios] Reply is not set. Make sure to set it before using it.',\n )\n }\n return this.reply\n }\n\n provideRequest(request: FastifyRequest): void {\n this.request = request\n }\n provideReply(reply: FastifyReply): void {\n this.reply = reply\n }\n}\n","import type { CanActivate } from '../interfaces/index.mjs'\nimport type { ClassTypeWithInstance } from '../service-locator/index.mjs'\nimport type { ExecutionContext } from './execution-context.mjs'\n\nimport { HttpException } from '../exceptions/index.mjs'\nimport {\n inject,\n Injectable,\n InjectionToken,\n} from '../service-locator/index.mjs'\n\n@Injectable()\nexport class GuardRunnerService {\n async runGuards(\n allGuards: Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >,\n executionContext: ExecutionContext,\n ) {\n let canActivate = true\n for (const guard of Array.from(allGuards).reverse()) {\n const guardInstance = await inject(\n guard as InjectionToken<CanActivate, undefined>,\n )\n if (!guardInstance.canActivate) {\n throw new Error(\n `[Navios] Guard ${guard.name as string} does not implement canActivate()`,\n )\n }\n try {\n canActivate = await guardInstance.canActivate(executionContext)\n if (!canActivate) {\n break\n }\n } catch (error) {\n if (error instanceof HttpException) {\n executionContext\n .getReply()\n .status(error.statusCode)\n .send(error.response)\n return false\n } else {\n executionContext\n .getReply()\n .status(500)\n .send({\n message: 'Internal server error',\n error: (error as Error).message,\n })\n return false\n }\n }\n }\n if (!canActivate) {\n executionContext.getReply().status(403).send({\n message: 'Forbidden',\n })\n return false\n }\n return canActivate\n }\n\n makeContext(\n executionContext: ExecutionContext,\n ): Set<\n ClassTypeWithInstance<CanActivate> | InjectionToken<CanActivate, undefined>\n > {\n const guards = new Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >()\n const endpointGuards = executionContext.getHandler().guards\n const controllerGuards = executionContext.getController().guards\n const moduleGuards = executionContext.getModule().guards\n if (endpointGuards.size > 0) {\n for (const guard of endpointGuards) {\n guards.add(guard)\n }\n }\n if (controllerGuards.size > 0) {\n for (const guard of controllerGuards) {\n guards.add(guard)\n }\n }\n if (moduleGuards.size > 0) {\n for (const guard of moduleGuards) {\n guards.add(guard)\n }\n }\n return guards\n }\n}\n","import type { NaviosModule } from '../interfaces/index.mjs'\nimport type { ModuleMetadata } from '../metadata/index.mjs'\nimport type { ClassTypeWithInstance } from '../service-locator/index.mjs'\n\nimport { Logger } from '../logger/index.mjs'\nimport { extractModuleMetadata } from '../metadata/index.mjs'\nimport { inject, Injectable, syncInject } from '../service-locator/index.mjs'\n\n@Injectable()\nexport class ModuleLoaderService {\n private logger = syncInject(Logger, {\n context: ModuleLoaderService.name,\n })\n private modulesMetadata: Map<string, ModuleMetadata> = new Map()\n private loadedModules: Map<string, any> = new Map()\n private initialized = false\n\n async loadModules(appModule: ClassTypeWithInstance<NaviosModule>) {\n if (this.initialized) {\n return\n }\n await this.traverseModules(appModule)\n this.initialized = true\n }\n\n private async traverseModules(\n module: ClassTypeWithInstance<NaviosModule>,\n parentMetadata?: ModuleMetadata,\n ) {\n const metadata = extractModuleMetadata(module)\n if (parentMetadata) {\n this.mergeMetadata(metadata, parentMetadata)\n }\n const moduleName = module.name\n if (this.modulesMetadata.has(moduleName)) {\n return\n }\n this.modulesMetadata.set(moduleName, metadata)\n const imports = metadata.imports ?? new Set()\n const loadingPromises = Array.from(imports).map(async (importedModule) =>\n this.traverseModules(importedModule, metadata),\n )\n await Promise.all(loadingPromises)\n const instance = await inject(module)\n if (instance.onModuleInit) {\n await instance.onModuleInit()\n }\n this.logger.debug(`Module ${moduleName} loaded`)\n this.loadedModules.set(moduleName, instance)\n }\n\n private mergeMetadata(\n metadata: ModuleMetadata,\n parentMetadata: ModuleMetadata,\n ): void {\n if (parentMetadata.guards) {\n for (const guard of parentMetadata.guards) {\n metadata.guards.add(guard)\n }\n }\n if (parentMetadata.customAttributes) {\n for (const [key, value] of parentMetadata.customAttributes) {\n if (metadata.customAttributes.has(key)) {\n continue\n }\n metadata.customAttributes.set(key, value)\n }\n }\n }\n getAllModules(): Map<string, ModuleMetadata> {\n return this.modulesMetadata\n }\n}\n","import type { z, ZodType } from 'zod'\n\nimport type {\n ControllerMetadata,\n EndpointMetadata,\n ModuleMetadata,\n} from './metadata/index.mjs'\nimport type { ClassType } from './service-locator/index.mjs'\n\nimport {\n getControllerMetadata,\n getEndpointMetadata,\n getModuleMetadata,\n hasControllerMetadata,\n hasModuleMetadata,\n} from './metadata/index.mjs'\n\nexport type ClassAttribute = (() => <T>(\n target: T,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n) => T) & {\n token: symbol\n}\nexport type ClassSchemaAttribute<T extends ZodType> = ((\n value: z.input<T>,\n) => <T extends ClassType>(\n target: T,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n) => T) & {\n token: symbol\n schema: ZodType\n}\n\nexport class AttributeFactory {\n static createAttribute(token: symbol): ClassAttribute\n static createAttribute<T extends ZodType>(\n token: symbol,\n schema: T,\n ): ClassSchemaAttribute<T>\n static createAttribute(token: symbol, schema?: ZodType) {\n const res =\n (value?: unknown) =>\n (\n target: any,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n ) => {\n if (context.kind !== 'class' && context.kind !== 'method') {\n throw new Error(\n '[Navios] Attribute can only be applied to classes or methods',\n )\n }\n const isController =\n context.kind === 'class' && hasControllerMetadata(target as ClassType)\n const isModule =\n context.kind === 'class' && hasModuleMetadata(target as ClassType)\n if (context.kind === 'class' && !isController && !isModule) {\n throw new Error(\n '[Navios] Attribute can only be applied to classes with @Controller or @Module decorators',\n )\n }\n let metadata =\n context.kind === 'class'\n ? isController\n ? getControllerMetadata(target as any, context)\n : getModuleMetadata(target as any, context)\n : getEndpointMetadata(target, context)\n if (schema) {\n const validatedValue = schema.safeParse(value)\n if (!validatedValue.success) {\n throw new Error(\n `[Navios] Invalid value for attribute ${token.toString()}: ${validatedValue.error}`,\n )\n }\n metadata.customAttributes.set(token, validatedValue.data)\n } else {\n metadata.customAttributes.set(token, true)\n }\n return target\n }\n res.token = token\n if (schema) {\n res.schema = schema\n }\n return res\n }\n\n static get(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ): true | null\n static get<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ): z.output<T> | null\n static get(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ) {\n return target.customAttributes.get(attribute.token) ?? null\n }\n\n static getAll(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ): Array<true> | null\n static getAll<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ): Array<z.output<T>> | null\n static getAll(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ) {\n const values = Array.from(target.customAttributes.entries())\n .filter(([key]) => key === attribute.token)\n .map(([, value]) => value)\n return values.length > 0 ? values : null\n }\n\n static getLast(\n attribute: ClassAttribute,\n target: (ModuleMetadata | ControllerMetadata | EndpointMetadata)[],\n ): true | null\n static getLast<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: (ModuleMetadata | ControllerMetadata | EndpointMetadata)[],\n ): z.output<T> | null\n static getLast(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: (ModuleMetadata | ControllerMetadata | EndpointMetadata)[],\n ) {\n for (let i = target.length - 1; i >= 0; i--) {\n const value = target[i].customAttributes.get(attribute.token)\n if (value) {\n return value\n }\n }\n return null\n }\n\n static has(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ): boolean\n static has<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ): boolean\n static has(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | EndpointMetadata,\n ) {\n return target.customAttributes.has(attribute.token)\n }\n}\n","import type { FastifyCorsOptions } from '@fastify/cors'\nimport type {\n FastifyInstance,\n FastifyListenOptions,\n FastifyServerOptions,\n} from 'fastify'\n\nimport cors from '@fastify/cors'\nimport { fastify } from 'fastify'\nimport {\n serializerCompiler,\n validatorCompiler,\n} from 'fastify-type-provider-zod'\n\nimport type { NaviosModule } from './interfaces/index.mjs'\nimport type { LoggerService, LogLevel } from './logger/index.mjs'\nimport type { ClassTypeWithInstance } from './service-locator/index.mjs'\n\nimport { HttpException } from './exceptions/index.mjs'\nimport { Logger, PinoWrapper } from './logger/index.mjs'\nimport {\n getServiceLocator,\n inject,\n Injectable,\n syncInject,\n} from './service-locator/index.mjs'\nimport {\n ControllerAdapterService,\n ModuleLoaderService,\n} from './services/index.mjs'\nimport { Application } from './tokens/index.mjs'\n\nexport interface NaviosApplicationContextOptions {\n /**\n * Specifies the logger to use. Pass `false` to turn off logging.\n */\n logger?: LoggerService | LogLevel[] | false\n}\n\nexport interface NaviosApplicationOptions\n extends Omit<FastifyServerOptions, 'logger'>,\n NaviosApplicationContextOptions {}\n\n@Injectable()\nexport class NaviosApplication {\n private moduleLoader = syncInject(ModuleLoaderService)\n private controllerAdapter = syncInject(ControllerAdapterService)\n private logger = syncInject(Logger, {\n context: NaviosApplication.name,\n })\n private server: FastifyInstance | null = null\n private corsOptions: FastifyCorsOptions | null = null\n private globalPrefix: string | null = null\n\n private appModule: ClassTypeWithInstance<NaviosModule> | null = null\n private options: NaviosApplicationOptions = {}\n\n setup(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: NaviosApplicationOptions = {},\n ) {\n this.appModule = appModule\n this.options = options\n }\n\n async init() {\n if (!this.appModule) {\n throw new Error('App module is not set. Call setAppModule() first.')\n }\n await this.moduleLoader.loadModules(this.appModule)\n this.server = await this.getFastifyInstance(this.options)\n this.configureFastifyInstance(this.server)\n getServiceLocator().registerInstance(Application, this.server)\n // Add schema validator and serializer\n this.server.setValidatorCompiler(validatorCompiler)\n this.server.setSerializerCompiler(serializerCompiler)\n\n if (this.corsOptions) {\n await this.server.register(cors, this.corsOptions)\n }\n\n await this.initModules()\n await this.server.ready()\n\n this.logger.debug('Navios application initialized')\n }\n\n private async getFastifyInstance(rawOptions: NaviosApplicationOptions) {\n const { logger, ...options } = rawOptions\n if (logger) {\n const fastifyOptions = options as FastifyServerOptions\n if (typeof logger === 'boolean') {\n if (!logger) {\n fastifyOptions.logger = false\n }\n } else {\n fastifyOptions.loggerInstance = new PinoWrapper(\n await inject(Logger, {\n context: 'FastifyAdapter',\n }),\n )\n }\n return fastify(fastifyOptions)\n } else {\n return fastify({\n ...options,\n loggerInstance: new PinoWrapper(\n await inject(Logger, {\n context: 'FastifyAdapter',\n }),\n ),\n } as FastifyServerOptions)\n }\n }\n\n private configureFastifyInstance(fastifyInstance: FastifyInstance) {\n fastifyInstance.setErrorHandler((error, request, reply) => {\n if (error instanceof HttpException) {\n return reply.status(error.statusCode).send(error.response)\n } else {\n const statusCode = error.statusCode || 500\n const message = error.message || 'Internal Server Error'\n const response = {\n statusCode,\n message,\n error: error.name || 'InternalServerError',\n }\n this.logger.error(\n `Error occurred: ${error.message} on ${request.url}`,\n error,\n )\n return reply.status(statusCode).send(response)\n }\n })\n\n fastifyInstance.setNotFoundHandler((req, reply) => {\n const response = {\n statusCode: 404,\n message: 'Not Found',\n error: 'NotFound',\n }\n this.logger.error(`Route not found: ${req.url}`)\n return reply.status(404).send(response)\n })\n }\n\n private async initModules() {\n const modules = this.moduleLoader.getAllModules()\n const promises: PromiseLike<any>[] = []\n for (const [moduleName, moduleMetadata] of modules) {\n if (\n !moduleMetadata.controllers ||\n moduleMetadata.controllers.size === 0\n ) {\n continue\n }\n promises.push(\n this.server!.register(\n (instance, opts, done) => {\n for (const controller of moduleMetadata.controllers) {\n this.controllerAdapter.setupController(\n controller,\n instance,\n moduleMetadata,\n )\n }\n done()\n },\n {\n prefix: this.globalPrefix ?? '',\n },\n ),\n )\n }\n\n await Promise.all(promises)\n }\n\n enableCors(options: FastifyCorsOptions) {\n this.corsOptions = options\n }\n\n setGlobalPrefix(prefix: string) {\n this.globalPrefix = prefix\n }\n\n getServer(): FastifyInstance {\n if (!this.server) {\n throw new Error('Server is not initialized. Call init() first.')\n }\n return this.server\n }\n\n async listen(options: FastifyListenOptions) {\n if (!this.server) {\n throw new Error('Server is not initialized. Call init() first.')\n }\n const res = await this.server.listen(options)\n this.logger.debug(`Navios is listening on ${res}`)\n }\n}\n","import type { NaviosModule } from './interfaces/index.mjs'\nimport type {\n NaviosApplicationContextOptions,\n NaviosApplicationOptions,\n} from './navios.application.mjs'\nimport type { ClassTypeWithInstance } from './service-locator/index.mjs'\n\nimport { isNil, LoggerInstance } from './logger/index.mjs'\nimport { NaviosApplication } from './navios.application.mjs'\nimport { inject } from './service-locator/index.mjs'\n\nexport class NaviosFactory {\n static async create(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: NaviosApplicationOptions = {},\n ) {\n const app = await inject(NaviosApplication)\n this.registerLoggerConfiguration(options)\n app.setup(appModule, options)\n return app\n }\n\n private static registerLoggerConfiguration(\n options: NaviosApplicationContextOptions,\n ) {\n if (!options) {\n return\n }\n const { logger } = options\n if ((logger as boolean) !== true && !isNil(logger)) {\n LoggerInstance.overrideLogger(logger)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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UACP;AAAA,UACA;AAAA,YACE,QAAQ,KAAK,gBAAgB;AAAA,UAC/B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,UAAM,QAAQ,IAAI,QAAQ;AAAA,EAC5B;AAAA,EAEA,WAAW,SAA6B;AACtC,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,gBAAgB,QAAgB;AAC9B,SAAK,eAAe;AAAA,EACtB;AAAA,EAEA,YAA6B;AAC3B,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,IAAI,MAAM,+CAA+C;AAAA,IACjE;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,OAAO,SAA+B;AAC1C,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,IAAI,MAAM,+CAA+C;AAAA,IACjE;AACA,UAAM,MAAM,MAAM,KAAK,OAAO,OAAO,OAAO;AAC5C,SAAK,OAAO,MAAM,0BAA0B,GAAG,EAAE;AAAA,EACnD;AACF;AA5JOD,SAAA;AAAM,qBAAN,kBAAAA,QAAA,wBADP,+BACa;AAAN,kBAAAA,QAAA,GAAM;AAAN,IAAM,oBAAN;;;ACjCA,IAAM,gBAAN,MAAoB;AAAA,EACzB,aAAa,OACX,WACA,UAAoC,CAAC,GACrC;AACA,UAAM,MAAM,MAAM,OAAO,iBAAiB;AAC1C,SAAK,4BAA4B,OAAO;AACxC,QAAI,MAAM,WAAW,OAAO;AAC5B,WAAO;AAAA,EACT;AAAA,EAEA,OAAe,4BACb,SACA;AACA,QAAI,CAAC,SAAS;AACZ;AAAA,IACF;AACA,UAAM,EAAE,OAAO,IAAI;AACnB,QAAK,WAAuB,QAAQ,CAAC,MAAM,MAAM,GAAG;AAClD,qBAAe,eAAe,MAAM;AAAA,IACtC;AAAA,EACF;AACF;","names":["ExecutionContext","import_zod","import_common","InjectableScope","name","ErrorsEnum","name","name","name","name","name","_a","res","ServiceLocatorInstanceHolderKind","ServiceLocatorInstanceHolderStatus","name","name","_a","instanceName","serviceLocator","promiseCollector","InjectableType","serviceLocator","import_zod","dateTimeFormatter","_init","_init","import_common","_init","EndpointType","name","import_common","ExecutionContext","module","_init","_init","ExecutionContext","_init","module","_init","cors"]}
|