@navios/commander 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/lib/index.cjs +556 -172
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts.map +1 -1
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +548 -173
- package/lib/index.mjs.map +1 -1
- package/package.json +2 -2
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["EndpointMetadataKey","Symbol","getAllEndpointMetadata","context","metadata","Set","Error","getEndpointMetadata","target","endpointMetadata","Array","from","find","item","classMethod","name","newMetadata","url","successStatusCode","adapterToken","headers","httpMethod","config","guards","customAttributes","Map","add","getAllEndpointMetadata","ControllerMetadataKey","Symbol","getControllerMetadata","target","context","metadata","endpointsMetadata","newMetadata","endpoints","guards","Set","customAttributes","Map","Error","extractControllerMetadata","hasControllerMetadata","ModuleMetadataKey","Symbol","getModuleMetadata","target","context","metadata","newMetadata","controllers","Set","imports","guards","customAttributes","Map","Error","extractModuleMetadata","name","hasModuleMetadata","Injectable","InjectableScope","InjectionToken","getControllerMetadata","Controller","guards","target","context","kind","Error","token","create","metadata","controllerMetadata","guard","Array","from","reverse","add","scope","Request","InjectionToken","EndpointAdapterToken","create","InjectionToken","ExecutionContextInjectionToken","ExecutionContext","create","InjectionToken","HttpAdapterToken","create","InjectionToken","MultipartAdapterToken","create","InjectionToken","Reply","create","InjectionToken","Request","create","InjectionToken","StreamAdapterToken","create","InjectionToken","XmlStreamAdapterToken","create","getEndpointMetadata","EndpointAdapterToken","Endpoint","endpoint","target","context","kind","Error","config","metadata","endpointMetadata","url","method","adapterToken","classMethod","name","httpMethod","getEndpointMetadata","Header","name","value","target","context","kind","Error","metadata","headers","getEndpointMetadata","HttpCode","code","target","context","kind","Error","metadata","successStatusCode","Injectable","InjectableScope","InjectionToken","getModuleMetadata","Module","controllers","imports","guards","target","context","kind","Error","token","create","moduleMetadata","controller","add","importedModule","guard","Array","from","reverse","scope","Singleton","getEndpointMetadata","MultipartAdapterToken","Multipart","endpoint","target","context","Error","kind","config","metadata","endpointMetadata","url","method","adapterToken","classMethod","name","httpMethod","getEndpointMetadata","StreamAdapterToken","Stream","endpoint","target","context","Error","kind","config","metadata","endpointMetadata","url","method","adapterToken","classMethod","name","httpMethod","getControllerMetadata","getEndpointMetadata","UseGuards","guards","target","context","kind","controllerMetadata","guard","reverse","add","endpointMetadata","Error","client: Client | null","LOG_LEVELS","LOG_LEVELS","isLogLevel","maybeLogLevel","includes","LOG_LEVELS","isLogLevel","filterLogLevels","parseableString","sanitizedString","replaceAll","toLowerCase","orEqual","logLevelIndex","indexOf","substring","Error","slice","includes","split","filter","LOG_LEVEL_VALUES","verbose","debug","log","warn","error","fatal","isLogLevelEnabled","targetLevel","logLevels","Array","isArray","length","includes","highestLogLevelValue","map","level","sort","a","b","targetLevelValue","AsyncLocalStorage","requestIdStore","runWithRequestId","requestId","fn","run","getRequestId","getStore","InjectionToken","z","LoggerOutput","create","loggerOptionsSchema","object","context","string","optional","Logger","inspect","Injectable","getRequestId","LoggerOutput","clc","isFunction","isLogLevelEnabled","isPlainObject","isString","isUndefined","yellow","DEFAULT_DEPTH","DEFAULT_LOG_LEVELS","dateTimeFormatter","Intl","DateTimeFormat","undefined","year","hour","minute","second","day","month","token","ConsoleLogger","options","context","originalContext","inspectOptions","getInspectOptions","lastTimestampAt","setup","contextOrOptions","opts","logLevels","colors","json","prefix","log","message","optionalParams","isLevelEnabled","messages","getContextAndMessagesToPrint","printMessages","error","stack","getContextAndStackAndMessagesToPrint","printStackTrace","warn","debug","verbose","fatal","setLogLevels","levels","setContext","resetContext","level","getCurrentRequestId","requestId","getTimestamp","format","Date","now","logLevel","writeStreamType","errorStack","resolvedRequestId","forEach","printAsJson","pidMessage","formatPid","process","pid","contextMessage","formatContext","timestampDiff","updateAndGetTimestampDiff","formattedLogLevel","toUpperCase","padStart","formattedMessage","formatMessage","write","logObject","timestamp","compact","JSON","stringify","stringifyReplacer","output","stringifyMessage","colorize","messageAsStr","Function","prototype","toString","call","isClass","startsWith","name","outputText","Object","keys","length","Array","isArray","color","getColorByLogLevel","stderr","includeTimestamp","result","formatTimestampDiff","formattedDiff","breakLength","Infinity","depth","sorted","showHidden","maxArrayLength","maxStringLength","key","value","Map","Set","Error","args","lastElement","isContext","slice","isStackFormat","isStack","test","magentaBright","red","cyanBright","bold","green","inject","Injectable","Logger","LoggerOutput","token","LoggerInstance","config","context","localInstance","error","message","optionalParams","length","undefined","concat","log","warn","debug","verbose","fatal","NaviosError","inject","Injectable","InjectionToken","z","Logger","ConfigServiceOptionsSchema","record","string","unknown","ConfigServiceToken","create","Symbol","for","token","ConfigService","config","logger","context","name","getConfig","get","key","parts","String","split","value","part","undefined","error","debug","getOrDefault","defaultValue","getOrThrow","errorMessage","message","env","InjectionToken","z","ConfigServiceOptionsSchema","ConfigServiceToken","ConfigProviderOptions","object","load","function","output","provideConfig","options","factory","EnvConfigProvider","bound","HttpException","statusCode","response","error","HttpException","BadRequestException","message","HttpException","ForbiddenException","message","HttpException","InternalServerErrorException","message","error","HttpException","NotFoundException","response","error","HttpException","UnauthorizedException","message","error","HttpException","ConflictException","message","error","inject","Injectable","HttpException","Logger","GuardRunnerService","logger","context","name","runGuards","allGuards","executionContext","canActivate","guard","Array","from","reverse","guardInstance","get","Error","error","getReply","status","statusCode","send","response","message","makeContext","moduleMetadata","controllerMetadata","endpoint","guards","Set","endpointGuards","controllerGuards","moduleGuards","size","add","Container","inject","Injectable","Logger","extractModuleMetadata","ModuleLoaderService","logger","context","name","container","modulesMetadata","Map","loadedModules","initialized","loadModules","appModule","traverseModules","module","parentMetadata","metadata","mergeMetadata","moduleName","has","set","imports","Set","loadingPromises","Array","from","map","importedModule","Promise","all","instance","get","onModuleInit","debug","error","guards","guard","add","customAttributes","key","value","getAllModules","dispose","clear","getControllerMetadata","getEndpointMetadata","getModuleMetadata","hasControllerMetadata","hasModuleMetadata","AttributeFactory","createAttribute","token","schema","res","value","target","context","kind","Error","isController","isModule","metadata","validatedValue","safeParse","success","toString","error","customAttributes","set","data","get","attribute","getAll","values","Array","from","entries","filter","key","map","length","getLast","i","has","Injectable","NaviosEnvironment","httpTokens","Map","setupHttpEnvironment","tokens","getHttpToken","token","get","hasHttpSetup","size","Factory","inject","NaviosEnvironment","EndpointAdapterToken","token","EndpointAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","HttpAdapterToken","token","HttpAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","MultipartAdapterToken","token","MultipartAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","InjectableScope","NaviosEnvironment","Request","token","scope","RequestFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","InjectableScope","NaviosEnvironment","Reply","token","scope","Request","ReplyFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","StreamAdapterToken","token","StreamAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","XmlStreamAdapterToken","token","XmlStreamAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Container","inject","Injectable","HttpAdapterToken","Logger","NaviosEnvironment","ModuleLoaderService","NaviosApplication","environment","moduleLoader","httpApplication","logger","context","name","container","appModule","options","adapter","plugins","isInitialized","setup","hasHttpSetup","get","getContainer","usePlugin","definition","push","init","Error","loadModules","setupHttpServer","initModules","initPlugins","ready","debug","modules","getAllModules","onModulesInit","length","server","getServer","globalPrefix","getGlobalPrefix","plugin","register","enableCors","enableMultipart","setGlobalPrefix","prefix","listen","dispose","close","Container","InjectableScope","InjectableType","isNil","LoggerOutput","NaviosApplication","NaviosEnvironment","NaviosFactory","create","appModule","options","adapter","container","registerLoggerConfiguration","adapters","Array","isArray","registerEnvironment","app","get","setup","environment","naviosEnvironment","httpTokens","setupHttpEnvironment","logger","loggerInstance","logLevels","getServiceLocator","getManager","storeCreatedHolder","toString","Class","Singleton","$","envInt","A","loggerOptionsSchema","B","isObject","C","ConfigServiceOptionsSchema","D","_ConsoleLogger","E","_LoggerInstance","F","isConstructor","G","normalizePath","H","isString","I","isEmpty","J","filterLogLevels","K","stripEndSlash","L","isFunction","M","requestIdStore","N","runWithRequestId","O","Logger","P","addLeadingSlash","Q","yellow","R","isNil","S","provideConfig","T","_ConfigService","U","isSymbol","V","isPlainObject","W","isUndefined","X","LOG_LEVELS","Y","isLogLevel","Z","clc","_","ForbiddenException","a","_ReplyFactory","b","ConfigProviderOptions","c","_HttpAdapterFactory","d","_ModuleLoaderService","et","envString","f","_GuardRunnerService","g","InternalServerErrorException","h","NotFoundException","i","_StreamAdapterFactory","j","getRequestId","k","LoggerOutput","l","_EndpointAdapterFactory","m","UnauthorizedException","n","_NaviosApplication","o","_RequestFactory","p","ConflictException","q","isLogLevelEnabled","r","_XmlStreamAdapterFactory","s","_MultipartAdapterFactory","t","NaviosFactory","u","AttributeFactory","v","BadRequestException","w","ConfigServiceToken","x","EnvConfigProvider","y","HttpException","z","isNumber","extractControllerMetadata","getAllEndpointMetadata","EndpointMetadataKey","getEndpointMetadata","ControllerMetadataKey","hasControllerMetadata","Controller","HttpCode","getModuleMetadata","XmlStreamAdapterToken","Reply","MultipartAdapterToken","EndpointAdapterToken","ExecutionContextInjectionToken","Module","StreamAdapterToken","ExecutionContext","Stream","Header","HttpAdapterToken","Multipart","Endpoint","UseGuards","Request","ModuleMetadataKey","getControllerMetadata","hasModuleMetadata","extractModuleMetadata","ConfigService","ConsoleLogger","EndpointAdapterFactory","GuardRunnerService","HttpAdapterFactory","LoggerInstance","ModuleLoaderService","MultipartAdapterFactory","NaviosApplication","ReplyFactory","RequestFactory","StreamAdapterFactory","XmlStreamAdapterFactory","CommanderExecutionContext","command","commandPath","options","getCommand","getCommandPath","getOptions","CommandMetadataKey","Symbol","getCommandMetadata","target","context","path","optionsSchema","metadata","newMetadata","customAttributes","Map","Error","extractCommandMetadata","hasCommandMetadata","CliModuleMetadataKey","Symbol","getCliModuleMetadata","target","context","metadata","newMetadata","commands","Set","imports","customAttributes","Map","Error","extractCliModuleMetadata","name","hasCliModuleMetadata","Container","inject","Injectable","extractCliModuleMetadata","extractCommandMetadata","CliModuleLoaderService","container","modulesMetadata","Map","loadedModules","commandsMetadata","initialized","loadModules","appModule","traverseModules","module","parentMetadata","metadata","mergeMetadata","moduleName","name","has","set","command","commands","commandMetadata","path","class","imports","Set","loadingPromises","Array","from","map","importedModule","Promise","all","instance","get","onModuleInit","customAttributes","key","value","getAllModules","getAllCommands","values","getAllCommandsWithMetadata","getCommandByPath","dispose","clear","Injectable","CliParserService","parse","argv","optionsSchema","args","slice","length","Error","booleanFields","extractBooleanFields","Set","arrayFields","extractArrayFields","commandParts","i","startsWith","push","command","join","options","positionals","arg","key","equalIndex","indexOf","optionName","optionValue","camelCaseKey","camelCase","isArray","has","parseValue","isBoolean","nextArg","flags","flag","str","replace","_","letter","toUpperCase","value","undefined","test","parseInt","parseFloat","endsWith","JSON","schema","typeName","def","type","shape","fieldSchema","Object","entries","isSchemaBoolean","add","isSchemaArray","currentSchema","_def","innerType","innerTypeName","formatCommandList","commands","lines","path","InjectionToken","CommandExecutionContextInjectionToken","CommandExecutionContext","create","Container","inject","Injectable","CommanderExecutionContext","CliModuleLoaderService","CliParserService","CommandExecutionContext","CommanderApplication","moduleLoader","cliParser","container","appModule","options","isInitialized","setup","getContainer","init","Error","loadModules","executeCommand","commandPath","commandWithMetadata","getCommandByPath","class","commandClass","metadata","validatedOptions","optionsSchema","parse","executionContext","requestId","Date","now","Math","random","toString","substring","scopeContainer","beginRequest","addInstance","commandInstance","get","execute","endRequest","getAllCommands","commandsMap","getAllCommandsWithMetadata","commandsWithMetadata","cmd","push","path","run","argv","process","preliminaryParse","command","parsed","help","h","commands","console","log","formatCommandList","error","message","includes","dispose","close","Container","CommanderApplication","CommanderFactory","create","appModule","options","container","app","get","setup","Injectable","InjectableScope","InjectionToken","getCommandMetadata","Command","path","optionsSchema","target","context","kind","Error","token","create","metadata","scope","Singleton","Injectable","InjectableScope","InjectionToken","getCliModuleMetadata","CliModule","commands","imports","target","context","kind","Error","token","create","moduleMetadata","command","add","importedModule","scope","Singleton"],"sources":["../../src/metadata/handler.metadata.mts","../../src/metadata/controller.metadata.mts","../../src/metadata/module.metadata.mts","../../src/decorators/controller.decorator.mts","../../src/tokens/endpoint-adapter.token.mts","../../src/tokens/execution-context.token.mts","../../src/tokens/http-adapter.token.mts","../../src/tokens/multipart-adapter.token.mts","../../src/tokens/reply.token.mts","../../src/tokens/request.token.mts","../../src/tokens/stream-adapter.token.mts","../../src/tokens/xml-stream-adapter.token.mts","../../src/decorators/endpoint.decorator.mts","../../src/decorators/header.decorator.mts","../../src/decorators/http-code.decorator.mts","../../src/decorators/module.decorator.mts","../../src/decorators/multipart.decorator.mts","../../src/decorators/stream.decorator.mts","../../src/decorators/use-guards.decorator.mts","../../src/errors/navios-error.mts","../../src/errors/handle-error.mts","../../src/request/bind-url-params.mts","../../src/request/make-config.mts","../../src/handlers/create-handler.mts","../../src/handlers/endpoint.mts","../../src/handlers/multipart.mts","../../src/handlers/stream.mts","../../src/builder.mts","../../src/config/utils/helpers.mts","../../src/logger/utils/cli-colors.util.mts","../../src/logger/log-levels.mts","../../src/logger/utils/is-log-level.util.mts","../../src/logger/utils/filter-log-levelts.util.mts","../../src/logger/utils/is-log-level-enabled.mts","../../src/logger/utils/shared.utils.mts","../../src/stores/request-id.store.mts","../../src/logger/logger.tokens.mts","../../src/logger/console-logger.service.mts","../../src/logger/logger.service.mts","../../src/config/config.service.mts","../../src/config/config.provider.mts","../../src/exceptions/http.exception.mts","../../src/exceptions/bad-request.exception.mts","../../src/exceptions/forbidden.exception.mts","../../src/exceptions/internal-server-error.exception.mts","../../src/exceptions/not-found.exception.mts","../../src/exceptions/unauthorized.exception.mts","../../src/exceptions/conflict.exception.mts","../../src/services/guard-runner.service.mts","../../src/services/module-loader.service.mts","../../src/attribute.factory.mts","../../src/navios.environment.mts","../../src/factories/endpoint-adapter.factory.mts","../../src/factories/http-adapter.factory.mts","../../src/factories/multipart-adapter.factory.mts","../../src/factories/request.factory.mts","../../src/factories/reply.factory.mts","../../src/factories/stream-adapter.factory.mts","../../src/factories/xml-stream-adapter.factory.mts","../../src/navios.application.mts","../../src/navios.factory.mts","../../core/lib/index.mjs","../src/interfaces/commander-execution-context.interface.mts","../src/metadata/command.metadata.mts","../src/metadata/cli-module.metadata.mts","../src/services/module-loader.service.mts","../src/services/cli-parser.service.mts","../src/tokens/execution-context.token.mts","../src/commander.application.mts","../src/commander.factory.mts","../src/decorators/command.decorator.mts","../src/decorators/cli-module.decorator.mts","../src/index.mts"],"sourcesContent":["import type { HttpMethod } from '@navios/builder'\nimport type { ClassTypeWithInstance, InjectionToken } from '@navios/di'\n\nimport type {\n AbstractHttpHandlerAdapterInterface,\n CanActivate,\n HttpHeader,\n} from '../interfaces/index.mjs'\n\nexport const EndpointMetadataKey = Symbol('EndpointMetadataKey')\n\nexport interface HandlerMetadata<Config = null> {\n classMethod: string\n url: string\n successStatusCode: number\n adapterToken:\n | InjectionToken<AbstractHttpHandlerAdapterInterface, undefined>\n | ClassTypeWithInstance<AbstractHttpHandlerAdapterInterface>\n | null\n headers: Partial<Record<HttpHeader, number | string | string[] | undefined>>\n httpMethod: HttpMethod\n config: Config\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<HandlerMetadata<any>> {\n if (context.metadata) {\n const metadata = context.metadata[EndpointMetadataKey] as\n | Set<HandlerMetadata>\n | undefined\n if (metadata) {\n return metadata\n } else {\n context.metadata[EndpointMetadataKey] = new Set<HandlerMetadata<any>>()\n return context.metadata[EndpointMetadataKey] as Set<HandlerMetadata<any>>\n }\n }\n throw new Error('[Navios] Wrong environment.')\n}\n\nexport function getEndpointMetadata<Config = any>(\n target: Function,\n context: ClassMethodDecoratorContext,\n): HandlerMetadata<Config> {\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: HandlerMetadata<Config> = {\n classMethod: target.name,\n url: '',\n successStatusCode: 200,\n adapterToken: null,\n headers: {},\n httpMethod: 'GET',\n // @ts-expect-error We are using a generic type here\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 {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport type { CanActivate } from '../interfaces/index.mjs'\nimport type { HandlerMetadata } from './handler.metadata.mjs'\n\nimport { getAllEndpointMetadata } from './handler.metadata.mjs'\n\nexport const ControllerMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ControllerMetadata {\n endpoints: Set<HandlerMetadata>\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 {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport type { CanActivate } from '../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 for ${target.name}. 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 '@navios/di'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/di'\n\nimport { getControllerMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a Navios controller.\n */\nexport interface ControllerOptions {\n /**\n * Guards to apply to all endpoints in this controller.\n * Guards are executed in reverse order (last guard first).\n */\n guards?: ClassType[] | Set<ClassType>\n}\n\n/**\n * Decorator that marks a class as a Navios controller.\n * \n * Controllers handle HTTP requests and define endpoints.\n * They are request-scoped by default, meaning a new instance is created for each request.\n * \n * @param options - Controller configuration options\n * @returns A class decorator\n * \n * @example\n * ```typescript\n * @Controller({ guards: [AuthGuard] })\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * // Handle request\n * }\n * }\n * ```\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 scope: InjectableScope.Request,\n })(target, context)\n }\n}\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const EndpointAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'EndpointAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractExecutionContext } from '../interfaces/index.mjs'\n\nexport const ExecutionContextInjectionToken = 'ExecutionContextInjectionToken'\n\nexport const ExecutionContext = InjectionToken.create<AbstractExecutionContext>(\n ExecutionContextInjectionToken,\n)\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpAdapterInterface } from '../interfaces/index.mjs'\n\nexport const HttpAdapterToken =\n InjectionToken.create<AbstractHttpAdapterInterface<any, any, any, any>>(\n 'HttpAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const MultipartAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'MultipartAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nexport const Reply = InjectionToken.create<any>('ReplyToken')\n","import { InjectionToken } from '@navios/di'\n\nexport const Request = InjectionToken.create<any>('RequestToken')\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const StreamAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'StreamAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const XmlStreamAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'XmlStreamAdapterToken',\n )\n","import type {\n BaseEndpointConfig,\n EndpointFunctionArgs,\n HttpMethod,\n Util_FlatObject,\n} from '@navios/builder'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { ZodDiscriminatedUnion } from 'zod/v4'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\nimport { EndpointAdapterToken } from '../tokens/index.mjs'\n\n/**\n * Extracts the typed parameters for an endpoint handler function.\n *\n * This utility type extracts URL parameters, query parameters, and request body\n * from an endpoint declaration and flattens them into a single object.\n *\n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n *\n * @example\n * ```typescript\n * const getUserEndpoint = api.declareEndpoint({\n * method: 'get',\n * url: '/users/$userId',\n * querySchema: z.object({ include: z.string().optional() }),\n * responseSchema: z.object({ id: z.string(), name: z.string() }),\n * })\n *\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * // request.urlParams.userId is typed as string\n * // request.query.include is typed as string | undefined\n * }\n * ```\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 ZodType\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, QuerySchema, undefined, true>>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, undefined, undefined, true>>\n\n/**\n * Extracts the typed return value for an endpoint handler function.\n *\n * This utility type extracts the response schema from an endpoint declaration\n * and returns the appropriate Promise type.\n *\n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n *\n * @example\n * ```typescript\n * const getUserEndpoint = api.declareEndpoint({\n * method: 'get',\n * url: '/users/$userId',\n * responseSchema: z.object({ id: z.string(), name: z.string() }),\n * })\n *\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>): EndpointResult<typeof getUserEndpoint> {\n * return { id: '1', name: 'John' } // Type-checked against responseSchema\n * }\n * ```\n */\nexport type EndpointResult<\n EndpointDeclaration extends {\n config: BaseEndpointConfig<any, any, any, any, any>\n },\n> =\n EndpointDeclaration['config']['responseSchema'] extends ZodDiscriminatedUnion<\n infer Options\n >\n ? Promise<z.input<Options[number]>>\n : Promise<z.input<EndpointDeclaration['config']['responseSchema']>>\n\n/**\n * Decorator that marks a method as an HTTP endpoint.\n *\n * The endpoint must be defined using @navios/builder's `declareEndpoint` method.\n * This ensures type safety and consistency between client and server.\n *\n * @param endpoint - The endpoint declaration from @navios/builder\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * import { builder } from '@navios/builder'\n *\n * const api = builder()\n * const getUserEndpoint = api.declareEndpoint({\n * method: 'get',\n * url: '/users/$userId',\n * responseSchema: z.object({ id: z.string(), name: z.string() }),\n * })\n *\n * @Controller()\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * const { userId } = request.urlParams\n * return { id: userId, name: 'John' }\n * }\n * }\n * ```\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 ZodType\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>,\n ) => Promise<z.input<ResponseSchema>>,\n context: ClassMethodDecoratorContext,\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<BaseEndpointConfig>(\n target,\n context,\n )\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.adapterToken = EndpointAdapterToken\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 '../interfaces/index.mjs'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that sets a custom HTTP response header for an endpoint.\n * \n * @param name - The header name (e.g., 'Content-Type', 'Cache-Control')\n * @param value - The header value (string, number, or array of strings)\n * @returns A method decorator\n * \n * @example\n * ```typescript\n * @Controller()\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * @Header('Cache-Control', 'max-age=3600')\n * async getUser() {\n * return { id: '1', name: 'John' }\n * }\n * }\n * ```\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\n metadata.headers[name] = value\n\n return target\n }\n}\n","import { getEndpointMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that sets a custom HTTP status code for successful responses.\n * \n * By default, endpoints return 200 OK. Use this decorator to return a different status code.\n * \n * @param code - The HTTP status code to return (e.g., 201, 204, 202)\n * @returns A method decorator\n * \n * @example\n * ```typescript\n * @Controller()\n * export class UserController {\n * @Endpoint(createUserEndpoint)\n * @HttpCode(201)\n * async createUser() {\n * return { id: '1', name: 'John' }\n * }\n * }\n * ```\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 '@navios/di'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/di'\n\nimport { getModuleMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a Navios module.\n */\nexport interface ModuleOptions {\n /**\n * Controllers to register in this module.\n * Controllers handle HTTP requests and define endpoints.\n */\n controllers?: ClassType[] | Set<ClassType>\n /**\n * Other modules to import into this module.\n * Imported modules' controllers and services become available.\n */\n imports?: ClassType[] | Set<ClassType>\n /**\n * Guards to apply to all controllers in this module.\n * Guards are executed in reverse order (last guard first).\n */\n guards?: ClassType[] | Set<ClassType>\n}\n\n/**\n * Decorator that marks a class as a Navios module.\n * \n * Modules are the basic building blocks of a Navios application.\n * They organize controllers, services, and other modules into logical units.\n * \n * @param options - Module configuration options\n * @returns A class decorator\n * \n * @example\n * ```typescript\n * @Module({\n * controllers: [UserController, AuthController],\n * imports: [DatabaseModule],\n * guards: [AuthGuard],\n * })\n * export class AppModule {}\n * ```\n */\nexport function Module(\n { controllers = [], imports = [], guards = [] }: ModuleOptions = {\n controllers: [],\n imports: [],\n guards: [],\n },\n) {\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 for (const controller of controllers) {\n moduleMetadata.controllers.add(controller)\n }\n for (const importedModule of imports) {\n moduleMetadata.imports.add(importedModule)\n }\n for (const guard of Array.from(guards).reverse()) {\n moduleMetadata.guards.add(guard)\n }\n\n return Injectable({\n token,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","import type {\n BaseEndpointConfig,\n EndpointFunctionArgs,\n HttpMethod,\n Util_FlatObject,\n} from '@navios/builder'\nimport type { z, ZodObject, ZodType } from 'zod/v4'\n\nimport { ZodDiscriminatedUnion } from 'zod/v4'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\nimport { MultipartAdapterToken } from '../tokens/index.mjs'\n\n/**\n * Extracts the typed parameters for a multipart endpoint handler function.\n * \n * Similar to `EndpointParams`, but specifically for multipart/form-data endpoints.\n * \n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n */\nexport type MultipartParams<\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 ZodObject\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, QuerySchema, undefined, true>>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, undefined, undefined, true>>\n\n/**\n * Extracts the typed return value for a multipart endpoint handler function.\n * \n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n */\nexport type MultipartResult<\n EndpointDeclaration extends {\n config: BaseEndpointConfig<any, any, any, any, any>\n },\n> =\n EndpointDeclaration['config']['responseSchema'] extends ZodDiscriminatedUnion<\n infer Options\n >\n ? Promise<z.input<Options[number]>>\n : Promise<z.input<EndpointDeclaration['config']['responseSchema']>>\n\n/**\n * Decorator that marks a method as a multipart/form-data endpoint.\n * \n * Use this decorator for endpoints that handle file uploads or form data.\n * The endpoint must be defined using @navios/builder's `declareMultipart` method.\n * \n * @param endpoint - The multipart endpoint declaration from @navios/builder\n * @returns A method decorator\n * \n * @example\n * ```typescript\n * const uploadFileEndpoint = api.declareMultipart({\n * method: 'post',\n * url: '/upload',\n * requestSchema: z.object({ file: z.instanceof(File) }),\n * responseSchema: z.object({ url: z.string() }),\n * })\n * \n * @Controller()\n * export class FileController {\n * @Multipart(uploadFileEndpoint)\n * async uploadFile(request: MultipartParams<typeof uploadFileEndpoint>) {\n * const { file } = request.data\n * // Handle file upload\n * return { url: 'https://example.com/file.jpg' }\n * }\n * }\n * ```\n */\nexport function Multipart<\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 ZodObject\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 ) => Promise<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<BaseEndpointConfig>(\n target,\n context,\n )\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.adapterToken = MultipartAdapterToken\n endpointMetadata.classMethod = target.name\n endpointMetadata.httpMethod = config.method\n endpointMetadata.url = config.url\n }\n return target\n }\n}\n","import type {\n BaseStreamConfig,\n EndpointFunctionArgs,\n HttpMethod,\n Util_FlatObject,\n} from '@navios/builder'\nimport type { ZodObject, ZodType } from 'zod/v4'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\nimport { StreamAdapterToken } from '../tokens/index.mjs'\n\n/**\n * Extracts the typed parameters for a stream endpoint handler function.\n * \n * Similar to `EndpointParams`, but specifically for streaming endpoints.\n * \n * @typeParam EndpointDeclaration - The stream endpoint declaration from @navios/builder\n */\nexport type StreamParams<\n EndpointDeclaration extends {\n config: BaseStreamConfig<any, any, any, any>\n },\n Url extends string = EndpointDeclaration['config']['url'],\n QuerySchema = EndpointDeclaration['config']['querySchema'],\n> = QuerySchema extends ZodObject\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, QuerySchema, undefined, true>>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, undefined, undefined, true>>\n\n/**\n * Decorator that marks a method as a streaming endpoint.\n * \n * Use this decorator for endpoints that stream data (e.g., file downloads, SSE).\n * The endpoint must be defined using @navios/builder's `declareStream` method.\n * \n * @param endpoint - The stream endpoint declaration from @navios/builder\n * @returns A method decorator\n * \n * @example\n * ```typescript\n * const downloadFileEndpoint = api.declareStream({\n * method: 'get',\n * url: '/files/$fileId',\n * })\n * \n * @Controller()\n * export class FileController {\n * @Stream(downloadFileEndpoint)\n * async downloadFile(request: StreamParams<typeof downloadFileEndpoint>, reply: any) {\n * const { fileId } = request.urlParams\n * // Stream file data to reply\n * }\n * }\n * ```\n */\nexport function Stream<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n RequestSchema = ZodType,\n>(endpoint: {\n config: BaseStreamConfig<Method, Url, QuerySchema, RequestSchema>\n}) {\n return (\n target: (\n params: QuerySchema extends ZodObject\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 reply: any,\n ) => Promise<void>,\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<BaseStreamConfig>(\n target,\n context,\n )\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.adapterToken = StreamAdapterToken\n endpointMetadata.classMethod = target.name\n endpointMetadata.httpMethod = config.method\n endpointMetadata.url = config.url\n }\n return target\n }\n}\n","import type {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport type { CanActivate } from '../interfaces/index.mjs'\n\nimport {\n getControllerMetadata,\n getEndpointMetadata,\n} from '../metadata/index.mjs'\n\n/**\n * Decorator that applies guards to a controller or endpoint.\n * \n * Guards are used for authentication, authorization, and request validation.\n * They implement the `CanActivate` interface and are executed before the endpoint handler.\n * Guards can be applied at the module, controller, or endpoint level.\n * \n * @param guards - Guard classes or injection tokens to apply\n * @returns A class or method decorator\n * \n * @example\n * ```typescript\n * // Apply to a controller\n * @Controller()\n * @UseGuards(AuthGuard, RoleGuard)\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * async getUser() { }\n * }\n * \n * // Apply to a specific endpoint\n * @Controller()\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * @UseGuards(AuthGuard)\n * async getUser() { }\n * }\n * ```\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","/**\n * Custom error class for Navios Builder errors.\n *\n * This error is thrown when:\n * - No HTTP client has been provided via `provideClient`\n * - Other builder-specific errors occur\n *\n * @example\n * ```ts\n * try {\n * API.getClient()\n * } catch (error) {\n * if (error instanceof NaviosError) {\n * console.error('Navios error:', error.message)\n * }\n * }\n * ```\n */\nexport class NaviosError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'NaviosError'\n }\n}\n\n/**\n * @deprecated Use NaviosError instead. Will be removed in next major version.\n */\nexport const NaviosException = NaviosError\n","import type { ZodType } from 'zod/v4'\n\nimport { ZodError } from 'zod/v4'\n\nimport type { AbstractResponse, BuilderConfig } from '../types/index.mjs'\n\n/**\n * Handles errors that occur during HTTP requests.\n *\n * This function implements the error handling strategy based on the builder configuration:\n * - Calls `onError` callback if provided (always called first)\n * - If `useDiscriminatorResponse` is `true` and the error has a response, attempts to parse\n * the error response using the same `responseSchema` as success responses\n * - Calls `onZodError` callback if validation fails\n * - Throws the error if it cannot be handled as a discriminated response\n *\n * @param config - Builder configuration containing error handling callbacks\n * @param error - The error that occurred (can be any type)\n * @param responseSchema - Optional Zod schema to validate error responses when\n * `useDiscriminatorResponse` is enabled\n * @returns The parsed error response data if `useDiscriminatorResponse` is enabled\n * and parsing succeeds, otherwise throws the error\n * @throws The original error or a ZodError if validation fails\n *\n * @example\n * ```ts\n * // With useDiscriminatorResponse: true\n * const result = handleError(\n * { useDiscriminatorResponse: true },\n * { response: { data: { status: 'error', message: 'Not found' } } },\n * z.discriminatedUnion('status', [\n * z.object({ status: z.literal('success'), data: z.any() }),\n * z.object({ status: z.literal('error'), message: z.string() })\n * ])\n * )\n * // Returns: { status: 'error', message: 'Not found' }\n * ```\n */\nexport function handleError(\n config: BuilderConfig,\n error: unknown,\n responseSchema?: ZodType,\n) {\n if (config.onError) {\n config.onError(error)\n }\n if (!config.useDiscriminatorResponse) {\n if (config.onZodError && error instanceof ZodError) {\n config.onZodError(error, undefined, undefined)\n }\n throw error\n }\n if (\n responseSchema &&\n typeof error === 'object' &&\n error &&\n 'response' in error &&\n error.response\n ) {\n const response = error.response as AbstractResponse<any>\n try {\n return responseSchema.parse(response.data)\n } catch (e) {\n if (config.onZodError) {\n config.onZodError(e as ZodError, response, error)\n }\n throw e\n }\n }\n throw error\n}\n\n/**\n * @deprecated Use handleError instead. Will be removed in next major version.\n */\nexport const handleException = handleError\n","import type { BaseEndpointConfig, NaviosZodRequest } from '../types/index.mjs'\n\n/**\n * Binds URL parameters to a URL template string.\n *\n * Replaces placeholders in the format `$paramName` with actual values from `urlParams`.\n * All parameter values are URL-encoded to ensure safe inclusion in URLs.\n *\n * @param urlPart - URL template with parameter placeholders (e.g., '/users/$userId/posts/$postId')\n * @param params - Request parameters object containing `urlParams` with parameter values\n * @returns The URL with parameters replaced and URL-encoded\n * @throws {Error} If required URL parameters are missing\n *\n * @example\n * ```ts\n * const url = bindUrlParams('/users/$userId/posts/$postId', {\n * urlParams: { userId: '123', postId: '456' }\n * })\n * // Returns: '/users/123/posts/456'\n *\n * // With special characters (automatically encoded)\n * const url2 = bindUrlParams('/search/$query', {\n * urlParams: { query: 'hello world' }\n * })\n * // Returns: '/search/hello%20world'\n * ```\n */\nexport function bindUrlParams<Url extends string>(\n urlPart: Url,\n params: NaviosZodRequest<BaseEndpointConfig<any, Url, any, any, any>>,\n) {\n const placement = /\\$([a-zA-Z0-9]+)/g\n const matches = Array.from(urlPart.matchAll(placement))\n\n if (matches.length === 0) {\n return urlPart\n }\n\n // Extract all required param names\n const requiredParams = matches.map(([, group]) => group)\n\n // Validate that urlParams exists and contains all required params\n if (!params.urlParams) {\n throw new Error(\n `Missing urlParams. Required parameters: ${requiredParams.join(', ')}`,\n )\n }\n\n // Validate that all required params are present\n const missingParams = requiredParams.filter(\n (param) => params.urlParams![param as string] === undefined,\n )\n if (missingParams.length > 0) {\n throw new Error(\n `Missing required URL parameters: ${missingParams.join(', ')}`,\n )\n }\n\n // Single-pass replacement using callback to avoid issues with values containing $\n const result = urlPart.replace(placement, (_, paramName: string) => {\n const value = params.urlParams![paramName]\n return encodeURIComponent(String(value))\n })\n\n return result as Url\n}\n","import type { ZodType } from 'zod/v4'\n\nimport type {\n AbstractRequestConfig,\n BaseStreamConfig,\n HttpMethod,\n NaviosZodRequest,\n} from '../types/index.mjs'\n\nfunction parseWithSchema(schema: ZodType | undefined, value: unknown): unknown {\n return schema ? schema.parse(value) : value\n}\n\n/**\n * Creates a request configuration object for the HTTP client.\n *\n * This function:\n * - Validates and parses query parameters using `querySchema` (if provided)\n * - Validates and parses request body data using `requestSchema` (if provided)\n * - Converts request data to FormData if `isMultipart` is true\n * - Merges all request properties (headers, signal, etc.) into the final config\n *\n * @param request - The request parameters object\n * @param options - Endpoint configuration containing schemas\n * @param method - HTTP method to use\n * @param finalUrlPart - The final URL with parameters bound\n * @param isMultipart - Whether to convert the request data to FormData\n * @returns A request configuration object compatible with the Client interface\n *\n * @internal\n */\nexport function makeConfig<Config extends BaseStreamConfig>(\n request: NaviosZodRequest<Config>,\n options: Config,\n method: HttpMethod,\n finalUrlPart: string,\n isMultipart = false,\n) {\n return {\n ...request,\n params: parseWithSchema(options.querySchema as ZodType | undefined, request.params ?? {}) as Record<string, unknown>,\n method,\n url: finalUrlPart,\n data: isMultipart\n ? makeFormData(request, options)\n : parseWithSchema(options.requestSchema as ZodType | undefined, request.data),\n } satisfies AbstractRequestConfig\n}\n\n/**\n * Serializes a value for inclusion in FormData.\n *\n * Handles various types:\n * - File instances are returned as-is\n * - null/undefined become empty strings\n * - Dates are converted to ISO strings\n * - Objects with toISOString or toJSON methods are serialized appropriately\n * - Other objects are JSON stringified\n * - Primitives are converted to strings\n *\n * @param value - The value to serialize\n * @returns A string representation or File instance\n * @internal\n */\nfunction serializeFormDataValue(value: unknown): string | File {\n if (value instanceof File) {\n return value\n }\n if (value == null) {\n return ''\n }\n if (typeof value === 'string') {\n return value\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value)\n }\n if (value instanceof Date) {\n return value.toISOString()\n }\n if (typeof value === 'object') {\n if ('toISOString' in value && typeof value.toISOString === 'function') {\n return value.toISOString()\n }\n if ('toJSON' in value && typeof value.toJSON === 'function') {\n return String(value.toJSON())\n }\n return JSON.stringify(value)\n }\n return String(value)\n}\n\n/**\n * Converts request data to FormData for multipart/form-data requests.\n *\n * The function:\n * - Validates the request data against `requestSchema` (if provided)\n * - Creates a FormData instance\n * - Appends all fields, handling File instances, arrays, and other types appropriately\n * - Files are appended with their name property\n * - Arrays of files are appended individually\n * - Other values are serialized using `serializeFormDataValue`\n *\n * @param request - The request parameters object\n * @param options - Endpoint configuration containing request schema\n * @returns A FormData instance ready for multipart requests\n *\n * @example\n * ```ts\n * const formData = makeFormData(\n * { data: { file: new File(['content'], 'file.txt'), name: 'My File' } },\n * { requestSchema: z.object({ file: z.instanceof(File), name: z.string() }) }\n * )\n * ```\n *\n * @internal\n */\nexport function makeFormData<Config extends BaseStreamConfig>(\n request: NaviosZodRequest<Config>,\n options: Config,\n) {\n const formData = new FormData()\n const validatedRequest = parseWithSchema(\n options.requestSchema as ZodType | undefined,\n request.data,\n ) as Record<string, unknown>\n for (const key in validatedRequest) {\n const value = validatedRequest[key]\n if (value instanceof File) {\n formData.append(key, value, value.name)\n } else if (Array.isArray(value)) {\n for (const item of value) {\n if (item instanceof File) {\n formData.append(key, item, item.name)\n } else {\n formData.append(key, serializeFormDataValue(item))\n }\n }\n } else {\n const serialized = serializeFormDataValue(value)\n if (serialized instanceof File) {\n formData.append(key, serialized, serialized.name)\n } else {\n formData.append(key, serialized)\n }\n }\n }\n return formData\n}\n","import type { ZodType } from 'zod/v4'\n\nimport type {\n BaseStreamConfig,\n BuilderContext,\n NaviosZodRequest,\n} from '../types/index.mjs'\n\nimport { handleError } from '../errors/handle-error.mjs'\nimport { bindUrlParams } from '../request/bind-url-params.mjs'\nimport { makeConfig } from '../request/make-config.mjs'\n\nexport interface CreateHandlerOptions<Config extends BaseStreamConfig> {\n options: Config\n context: BuilderContext\n isMultipart?: boolean\n responseSchema?: ZodType\n transformRequest?: (request: NaviosZodRequest<Config>) => NaviosZodRequest<Config>\n transformResponse?: (data: unknown) => unknown\n}\n\nexport function createHandler<Config extends BaseStreamConfig, TResponse>({\n options,\n context: { getClient, config },\n isMultipart = false,\n responseSchema,\n transformRequest,\n transformResponse,\n}: CreateHandlerOptions<Config>) {\n const { method, url } = options\n\n const handler = async (\n request: NaviosZodRequest<Config> = {} as NaviosZodRequest<Config>,\n ): Promise<TResponse> => {\n const client = getClient()\n const finalUrlPart = bindUrlParams<Config['url']>(url, request)\n const finalRequest = transformRequest ? transformRequest(request) : request\n\n try {\n const result = await client.request(\n makeConfig(finalRequest, options, method, finalUrlPart, isMultipart),\n )\n\n const data = transformResponse ? transformResponse(result.data) : result.data\n\n return (responseSchema ? responseSchema.parse(data) : data) as TResponse\n } catch (error) {\n // handleError may return a parsed response (when useDiscriminatorResponse is true)\n // or throw an error\n return handleError(config, error, responseSchema) as TResponse\n }\n }\n\n handler.config = options\n\n return handler\n}\n","import type { z } from 'zod/v4'\n\nimport type { BaseEndpointConfig, BuilderContext } from '../types/index.mjs'\n\nimport { createHandler } from './create-handler.mjs'\n\n/**\n * Creates an endpoint handler function with request/response validation.\n *\n * The returned function will:\n * - Validate request data against `requestSchema` (if provided)\n * - Validate query parameters against `querySchema` (if provided)\n * - Make the HTTP request using the configured client\n * - Validate and parse the response against `responseSchema`\n * - Handle errors according to the builder configuration\n *\n * @param options - Endpoint configuration\n * @param options.method - HTTP method (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)\n * @param options.url - URL pattern with optional parameters (e.g., '/users/$userId')\n * @param options.responseSchema - Zod schema for validating the response\n * @param options.requestSchema - Optional Zod schema for validating request body (POST, PUT, PATCH only)\n * @param options.querySchema - Optional Zod schema for validating query parameters\n * @param context - Builder context containing client getter and configuration\n * @returns A function that makes the HTTP request and returns validated response data\n *\n * @example\n * ```ts\n * const getUser = createEndpoint({\n * method: 'GET',\n * url: '/users/$userId',\n * responseSchema: z.object({ id: z.string(), name: z.string() })\n * }, context)\n *\n * const user = await getUser({ urlParams: { userId: '123' } })\n * ```\n */\nexport function createEndpoint<Config extends BaseEndpointConfig>(\n options: Config,\n context: BuilderContext,\n) {\n return createHandler<Config, z.output<Config['responseSchema']>>({\n options,\n context,\n responseSchema: options.responseSchema,\n })\n}\n","import type { z } from 'zod/v4'\n\nimport type { BaseEndpointConfig, BuilderContext } from '../types/index.mjs'\n\nimport { createHandler } from './create-handler.mjs'\n\n/**\n * Creates a multipart/form-data handler function for file uploads.\n *\n * The returned function will:\n * - Validate request data against `requestSchema` (if provided)\n * - Convert the request data to FormData automatically\n * - Handle File instances and other data types appropriately\n * - Validate query parameters against `querySchema` (if provided)\n * - Make the HTTP request with FormData\n * - Validate and parse the response against `responseSchema`\n *\n * @param options - Multipart endpoint configuration\n * @param options.method - HTTP method (POST, PUT, or PATCH)\n * @param options.url - URL pattern with optional parameters (e.g., '/upload/$userId')\n * @param options.responseSchema - Zod schema for validating the response\n * @param options.requestSchema - Optional Zod schema for validating request data (should include File types)\n * @param options.querySchema - Optional Zod schema for validating query parameters\n * @param context - Builder context containing client getter and configuration\n * @returns A function that makes the HTTP request with FormData and returns validated response data\n *\n * @example\n * ```ts\n * const uploadFile = createMultipart({\n * method: 'POST',\n * url: '/upload',\n * requestSchema: z.object({\n * file: z.instanceof(File),\n * description: z.string()\n * }),\n * responseSchema: z.object({ id: z.string(), url: z.string() })\n * }, context)\n *\n * const result = await uploadFile({\n * data: {\n * file: new File(['content'], 'file.txt'),\n * description: 'My file'\n * }\n * })\n * ```\n */\nexport function createMultipart<Config extends BaseEndpointConfig>(\n options: Config,\n context: BuilderContext,\n) {\n return createHandler<Config, z.output<Config['responseSchema']>>({\n options,\n context,\n isMultipart: true,\n responseSchema: options.responseSchema,\n })\n}\n","import type { BaseStreamConfig, BuilderContext, NaviosZodRequest } from '../types/index.mjs'\n\nimport { createHandler } from './create-handler.mjs'\n\n/**\n * Creates a stream handler function for downloading files as Blob.\n *\n * The returned function will:\n * - Validate request data against `requestSchema` (if provided)\n * - Validate query parameters against `querySchema` (if provided)\n * - Make the HTTP request with `responseType: 'blob'`\n * - Return the response as a Blob\n *\n * @param options - Stream endpoint configuration\n * @param options.method - HTTP method\n * @param options.url - URL pattern with optional parameters (e.g., '/files/$fileId')\n * @param options.requestSchema - Optional Zod schema for validating request body (POST, PUT, PATCH only)\n * @param options.querySchema - Optional Zod schema for validating query parameters\n * @param context - Builder context containing client getter and configuration\n * @returns A function that makes the HTTP request and returns a Blob\n *\n * @example\n * ```ts\n * const downloadFile = createStream({\n * method: 'GET',\n * url: '/files/$fileId',\n * querySchema: z.object({ format: z.enum(['pdf', 'docx']) })\n * }, context)\n *\n * const blob = await downloadFile({\n * urlParams: { fileId: '123' },\n * params: { format: 'pdf' }\n * })\n * ```\n */\nexport function createStream<Config extends BaseStreamConfig>(\n options: Config,\n context: BuilderContext,\n) {\n return createHandler<Config, Blob>({\n options,\n context,\n transformRequest: (request: NaviosZodRequest<Config>) => ({\n responseType: 'blob',\n ...request,\n }),\n transformResponse: (data) => data as Blob,\n })\n}\n","import type {\n BaseEndpointConfig,\n BaseStreamConfig,\n BuilderConfig,\n BuilderInstance,\n Client,\n} from './types/index.mjs'\n\nimport { NaviosError } from './errors/index.mjs'\nimport { createEndpoint, createMultipart, createStream } from './handlers/index.mjs'\n\n/**\n * Creates a new API builder instance with the specified configuration.\n *\n * The builder allows you to declaratively define API endpoints with type-safe\n * request and response schemas using Zod. It supports discriminated unions for\n * handling different response types, error handling callbacks, and various\n * HTTP methods.\n *\n * @param config - Configuration options for the builder\n * @param config.useDiscriminatorResponse - If `true`, error responses will be\n * parsed using the same responseSchema as success responses. This is useful\n * when your API returns discriminated unions that include both success and\n * error cases. Default is `false`.\n * @param config.onError - Optional callback function that will be called when\n * any error occurs during a request. This is called before the error is thrown\n * or processed.\n * @param config.onZodError - Optional callback function that will be called when\n * a Zod validation error occurs. This is called after `onError` if provided.\n * Useful for logging validation errors or showing user-friendly messages.\n *\n * @returns A BuilderInstance with methods to declare endpoints and manage the HTTP client\n *\n * @example\n * ```ts\n * const API = builder({\n * useDiscriminatorResponse: true,\n * onError: (error) => console.error('Request failed:', error),\n * onZodError: (error, response) => {\n * console.error('Validation failed:', error.errors)\n * }\n * })\n * ```\n */\nexport function builder(config: BuilderConfig = {}): BuilderInstance {\n let client: Client | null = null\n\n /**\n * Gets the current HTTP client instance.\n *\n * @returns The configured HTTP client\n * @throws {NaviosError} If no client has been provided via `provideClient`\n */\n function getClient() {\n if (!client) {\n throw new NaviosError('[Navios-API]: Client was not provided')\n }\n return client\n }\n\n /**\n * Declares a new API endpoint with request/response validation.\n *\n * @param options - Endpoint configuration\n * @returns A function that makes the HTTP request and returns validated response data\n */\n function declareEndpoint(options: BaseEndpointConfig) {\n return createEndpoint(options, {\n getClient,\n config,\n })\n }\n\n /**\n * Declares a new stream endpoint for downloading files as Blob.\n *\n * @param options - Stream endpoint configuration\n * @returns A function that makes the HTTP request and returns a Blob\n */\n function declareStream(options: BaseStreamConfig) {\n return createStream(options, {\n getClient,\n config,\n })\n }\n\n /**\n * Declares a new multipart/form-data endpoint for file uploads.\n *\n * The request data will be automatically converted to FormData.\n *\n * @param options - Multipart endpoint configuration\n * @returns A function that makes the HTTP request with FormData and returns validated response data\n */\n function declareMultipart(options: BaseEndpointConfig) {\n return createMultipart(options, {\n getClient,\n config,\n })\n }\n\n /**\n * Sets or replaces the HTTP client instance used by all endpoints.\n *\n * The client must implement the `Client` interface with a `request` method.\n * Compatible with axios, @navios/http, and any client that follows the same interface.\n *\n * @param newClient - The HTTP client instance to use for all requests\n *\n * @example\n * ```ts\n * import { create } from '@navios/http'\n * const client = create({ baseURL: 'https://api.example.com' })\n * API.provideClient(client)\n * ```\n */\n function provideClient(newClient: Client) {\n client = newClient\n }\n\n return {\n declareEndpoint,\n declareStream,\n declareMultipart,\n provideClient,\n getClient,\n }\n}\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","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","/**\n * Available log levels in order of severity (lowest to highest).\n */\nexport const LOG_LEVELS = [\n 'verbose',\n 'debug',\n 'log',\n 'warn',\n 'error',\n 'fatal',\n] as const satisfies string[]\n\n/**\n * Log level type.\n * \n * Represents the severity level of a log message.\n * Levels are: 'verbose', 'debug', 'log', 'warn', 'error', 'fatal'\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 { AsyncLocalStorage } from 'node:async_hooks'\n\n/**\n * AsyncLocalStorage store for the current request ID.\n *\n * This allows logging and other services to access the current request ID\n * without explicitly passing it through the call stack.\n *\n * @example\n * ```typescript\n * import { requestIdStore, runWithRequestId, getRequestId } from '@navios/core'\n *\n * // Run code with a request ID in context\n * runWithRequestId('req-123', () => {\n * // Inside this callback, getRequestId() returns 'req-123'\n * logger.log('Processing request') // Will include request ID if logger is configured\n * })\n *\n * // Get current request ID (returns undefined if not in a request context)\n * const currentId = getRequestId()\n * ```\n */\nexport const requestIdStore = new AsyncLocalStorage<string>()\n\n/**\n * Runs a function with a request ID in the async local storage context.\n *\n * @param requestId - The request ID to set for this context\n * @param fn - The function to run within this context\n * @returns The return value of the function\n */\nexport function runWithRequestId<R>(requestId: string, fn: () => R): R {\n return requestIdStore.run(requestId, fn)\n}\n\n/**\n * Gets the current request ID from the async local storage context.\n *\n * @returns The current request ID, or undefined if not in a request context\n */\nexport function getRequestId(): string | undefined {\n return requestIdStore.getStore()\n}\n","import { InjectionToken } from '@navios/di'\n\nimport z from 'zod/v4'\n\nimport type { LoggerService } from './logger-service.interface.mjs'\nimport type { LoggerInstance } from './logger.service.mjs'\n\n/**\n * Injection token for the logger output service.\n * \n * This token is used to provide a custom logger implementation.\n * By default, it's bound to ConsoleLogger.\n */\nexport const LoggerOutput = InjectionToken.create<LoggerService>('LoggerOutput')\n\n/**\n * Schema for logger options.\n */\nexport const loggerOptionsSchema = z\n .object({\n context: z.string().optional(),\n })\n .optional()\n\n/**\n * Options for creating a logger instance.\n */\nexport type LoggerOptions = z.infer<typeof loggerOptionsSchema>\n\n/**\n * Injection token for the Logger service.\n * \n * Use this token to inject a contextualized logger instance.\n * \n * @example\n * ```typescript\n * const logger = inject(Logger, { context: 'MyService' })\n * logger.log('Hello world') // Logs with context: [MyService]\n * ```\n */\nexport const Logger = InjectionToken.create<\n LoggerInstance,\n typeof loggerOptionsSchema\n>('Logger', loggerOptionsSchema)\n","import type { InspectOptions } from 'util'\n\nimport { inspect } from 'util'\n\nimport { Injectable } from '@navios/di'\n\nimport type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-service.interface.mjs'\n\nimport { getRequestId } from '../stores/request-id.store.mjs'\nimport { LoggerOutput } from './logger.tokens.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 add a request ID to the log message.\n */\n requestId?: boolean\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({\n token: LoggerOutput,\n})\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 = this.getInspectOptions()\n /**\n * The last timestamp at which the log message was printed.\n */\n protected lastTimestampAt?: number\n\n setup(): void\n setup(context: string): void\n setup(options: ConsoleLoggerOptions): void\n setup(context: string, options: ConsoleLoggerOptions): void\n setup(\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', undefined, '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 /**\n * Gets the current request ID from the AsyncLocalStorage store.\n * Only returns a value if the requestId option is enabled.\n */\n protected getCurrentRequestId(): string | undefined {\n if (!this.options.requestId) {\n return undefined\n }\n return getRequestId()\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 requestId?: string,\n writeStreamType?: 'stdout' | 'stderr',\n errorStack?: unknown,\n ) {\n const resolvedRequestId = requestId ?? this.getCurrentRequestId()\n messages.forEach((message) => {\n if (this.options.json) {\n this.printAsJson(message, {\n context,\n logLevel,\n writeStreamType,\n errorStack,\n requestId: resolvedRequestId,\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 resolvedRequestId,\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 requestId?: string\n },\n ) {\n type JsonLogObject = {\n level: LogLevel\n pid: number\n timestamp: number\n message: unknown\n context?: string\n stack?: unknown\n requestId?: string\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 if (this.options.requestId && options.requestId) {\n logObject.requestId = options.requestId\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 requestId?: 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.getRequestId(requestId)}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}\\n`\n }\n\n protected getRequestId(requestId?: string) {\n if (this.options.requestId && requestId) {\n return `(${this.colorize(requestId, 'log')}) `\n }\n return ''\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 = this.lastTimestampAt && this.options?.timestamp\n const result = includeTimestamp\n ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt!)\n : ''\n this.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 { inject, Injectable } from '@navios/di'\n\nimport type { LoggerService } from './logger-service.interface.mjs'\nimport type { LoggerOptions } from './logger.tokens.mjs'\n\nimport { Logger, LoggerOutput } from './logger.tokens.mjs'\n\n/**\n * Logger service instance that can be injected into services and controllers.\n * \n * Provides contextualized logging with automatic context injection.\n * The context is set when the logger is injected using the `inject` function.\n * \n * @example\n * ```typescript\n * @Injectable()\n * export class UserService {\n * private logger = inject(Logger, { context: UserService.name })\n * \n * async findUser(id: string) {\n * this.logger.log(`Finding user ${id}`)\n * // Logs with context: [UserService]\n * }\n * }\n * ```\n */\n@Injectable({\n token: Logger,\n})\nexport class LoggerInstance implements LoggerService {\n protected localInstance = inject(LoggerOutput)\n\n protected context?: string\n\n constructor(config: LoggerOptions = {}) {\n this.context = config.context\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","import { NaviosError } from '@navios/builder'\nimport { inject, Injectable, InjectionToken } from '@navios/di'\n\nimport { z } from 'zod/v4'\n\nimport type { ConfigServiceInterface as IConfigService } from './config-service.interface.mjs'\nimport type { Path, PathValue } from './types.mjs'\n\nimport { Logger } from '../logger/index.mjs'\n\n/**\n * Schema for validating configuration service options.\n */\nexport const ConfigServiceOptionsSchema = z.record(z.string(), z.unknown())\n/**\n * Type for configuration service options.\n */\nexport type ConfigServiceOptions = z.infer<typeof ConfigServiceOptionsSchema>\n\n/**\n * Injection token for ConfigService.\n */\nexport const ConfigServiceToken = InjectionToken.create<\n IConfigService,\n typeof ConfigServiceOptionsSchema\n>(Symbol.for('ConfigService'), ConfigServiceOptionsSchema)\n\n/**\n * Service for managing application configuration with type-safe access.\n *\n * Provides methods to access configuration values using dot-notation paths\n * with full TypeScript type inference.\n *\n * @typeParam Config - The configuration object type\n *\n * @example\n * ```typescript\n * interface AppConfig {\n * database: {\n * host: string\n * port: number\n * }\n * api: {\n * timeout: number\n * }\n * }\n *\n * @Injectable()\n * export class DatabaseService {\n * private config = inject(MyConfigService)\n *\n * connect() {\n * const host = this.config.getOrThrow('database.host')\n * const port = this.config.getOrDefault('database.port', 5432)\n * // host is typed as string, port is typed as number\n * }\n * }\n * ```\n */\n@Injectable({\n token: ConfigServiceToken,\n})\nexport class ConfigService<\n Config extends ConfigServiceOptions = Record<string, unknown>,\n> implements IConfigService<Config> {\n private readonly logger = inject(Logger, {\n context: ConfigService.name,\n })\n\n /**\n * Creates a new ConfigService instance.\n *\n * @param config - The configuration object\n */\n constructor(private config: Config = {} as Config) {}\n\n /**\n * Gets the entire configuration object.\n *\n * @returns The complete configuration object\n */\n getConfig(): Config {\n return this.config\n }\n\n /**\n * Gets a configuration value by key path.\n *\n * Returns `null` if the key is not found or if any part of the path is invalid.\n *\n * @param key - Dot-separated path to the configuration value (e.g., 'database.host')\n * @returns The configuration value or `null` if not found\n *\n * @example\n * ```typescript\n * const host = config.get('database.host') // string | null\n * const port = config.get('database.port') // number | null\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 /**\n * Gets a configuration value by key path, or returns a default value if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param defaultValue - Default value to return if the key is not found\n * @returns The configuration value or the default value\n *\n * @example\n * ```typescript\n * const port = config.getOrDefault('database.port', 5432) // number\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 /**\n * Gets a configuration value by key path, or throws an error if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param errorMessage - Optional custom error message\n * @returns The configuration value\n * @throws Error if the key is not found\n *\n * @example\n * ```typescript\n * const host = config.getOrThrow('database.host') // string (throws if not found)\n * const apiKey = config.getOrThrow('api.key', 'API key is required') // string\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 NaviosError(message)\n }\n\n return value\n }\n}\n","import { env } from 'node:process'\n\nimport { FactoryInjectionToken, InjectionToken } from '@navios/di'\n\nimport { z } from 'zod/v4'\n\nimport type { ConfigServiceOptions } from './config.service.mjs'\n\nimport {\n ConfigService,\n ConfigServiceOptionsSchema,\n ConfigServiceToken,\n} from './config.service.mjs'\n\n/**\n * Schema for configuration provider options.\n */\nexport const ConfigProviderOptions = z.object({\n load: z.function({ output: ConfigServiceOptionsSchema }),\n})\n\n/**\n * Creates a factory injection token for ConfigService that loads configuration asynchronously.\n *\n * Use this when you need to load configuration from a file, database, or other async source.\n *\n * @param options - Configuration provider options\n * @param options.load - Async function that loads and returns the configuration object\n * @returns A factory injection token for ConfigService\n *\n * @example\n * ```typescript\n * const MyConfigService = provideConfig({\n * load: async () => {\n * const config = await loadConfigFromFile('config.json')\n * return config\n * },\n * })\n *\n * // Use in module setup\n * container.bind(ConfigServiceToken).toFactory(configProvider)\n * ```\n */\nexport function provideConfig<ConfigMap extends ConfigServiceOptions>(\n options: z.input<typeof ConfigProviderOptions>,\n): FactoryInjectionToken<\n ConfigService<ConfigMap>,\n typeof ConfigServiceOptionsSchema\n> {\n return InjectionToken.factory(ConfigServiceToken, async () => options.load())\n}\n\n/**\n * Pre-configured ConfigService provider that uses environment variables.\n *\n * Provides a ConfigService instance bound to `process.env`.\n *\n * @example\n * ```typescript\n * // Use environment variables as configuration\n * container.bind(ConfigServiceToken).toValue(EnvConfigProvider)\n * ```\n */\nexport const EnvConfigProvider = InjectionToken.bound<\n ConfigService<Record<string, string>>,\n typeof ConfigServiceOptionsSchema\n>(ConfigServiceToken, {\n ...env,\n})\n","/**\n * Base exception class for all HTTP exceptions in Navios.\n * \n * All HTTP exception classes extend this base class. When thrown from an endpoint handler,\n * Navios will automatically convert it to an appropriate HTTP response with the specified\n * status code and response body.\n * \n * @example\n * ```typescript\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * const user = await this.userService.findById(request.urlParams.userId)\n * if (!user) {\n * throw new HttpException(404, 'User not found')\n * }\n * return user\n * }\n * ```\n */\nexport class HttpException {\n /**\n * Creates a new HttpException instance.\n * \n * @param statusCode - HTTP status code (e.g., 400, 404, 500)\n * @param response - Response body (string or object)\n * @param error - Optional underlying error for logging/debugging\n */\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\n/**\n * Exception that represents a 400 Bad Request HTTP error.\n * \n * Use this exception when the client's request is malformed or invalid.\n * \n * @example\n * ```typescript\n * @Endpoint(createUserEndpoint)\n * async createUser(request: EndpointParams<typeof createUserEndpoint>) {\n * if (!request.data.email) {\n * throw new BadRequestException('Email is required')\n * }\n * // ...\n * }\n * ```\n */\nexport class BadRequestException extends HttpException {\n /**\n * Creates a new BadRequestException.\n * \n * @param message - Error message or response object\n */\n constructor(message: string | object) {\n super(400, message)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 403 Forbidden HTTP error.\n * \n * Use this exception when the client is authenticated but does not have\n * permission to access the requested resource.\n * \n * @example\n * ```typescript\n * @Endpoint(deleteUserEndpoint)\n * @UseGuards(AuthGuard, RoleGuard)\n * async deleteUser(request: EndpointParams<typeof deleteUserEndpoint>) {\n * if (!this.userService.hasPermission(request.user, 'delete')) {\n * throw new ForbiddenException('Insufficient permissions')\n * }\n * // ...\n * }\n * ```\n */\nexport class ForbiddenException extends HttpException {\n /**\n * Creates a new ForbiddenException.\n * \n * @param message - Error message\n */\n constructor(message: string) {\n super(403, message)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 500 Internal Server Error HTTP error.\n * \n * Use this exception when an unexpected error occurs on the server.\n * Generally, you should let unhandled errors bubble up rather than catching\n * and rethrowing as InternalServerErrorException, as Navios will handle them appropriately.\n * \n * @example\n * ```typescript\n * @Endpoint(processPaymentEndpoint)\n * async processPayment(request: EndpointParams<typeof processPaymentEndpoint>) {\n * try {\n * return await this.paymentService.process(request.data)\n * } catch (error) {\n * this.logger.error('Payment processing failed', error)\n * throw new InternalServerErrorException('Payment processing failed', error)\n * }\n * }\n * ```\n */\nexport class InternalServerErrorException extends HttpException {\n /**\n * Creates a new InternalServerErrorException.\n * \n * @param message - Error message or response object\n * @param error - Optional underlying error for logging\n */\n constructor(message: string | object, error?: Error) {\n super(500, message, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 404 Not Found HTTP error.\n * \n * Use this exception when the requested resource does not exist.\n * \n * @example\n * ```typescript\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * const user = await this.userService.findById(request.urlParams.userId)\n * if (!user) {\n * throw new NotFoundException('User not found')\n * }\n * return user\n * }\n * ```\n */\nexport class NotFoundException extends HttpException {\n /**\n * Creates a new NotFoundException.\n * \n * @param response - Error message or response object\n * @param error - Optional underlying error for logging\n */\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\n/**\n * Exception that represents a 401 Unauthorized HTTP error.\n * \n * Use this exception when the client is not authenticated or authentication failed.\n * \n * @example\n * ```typescript\n * @Endpoint(getUserEndpoint)\n * @UseGuards(AuthGuard)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * if (!request.headers.authorization) {\n * throw new UnauthorizedException('Authentication required')\n * }\n * // ...\n * }\n * ```\n */\nexport class UnauthorizedException extends HttpException {\n /**\n * Creates a new UnauthorizedException.\n * \n * @param message - Error message or response object\n * @param error - Optional underlying error for logging\n */\n constructor(message: string | object, error?: Error) {\n super(401, message, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 409 Conflict HTTP error.\n * \n * Use this exception when the request conflicts with the current state of the resource\n * (e.g., trying to create a resource that already exists).\n * \n * @example\n * ```typescript\n * @Endpoint(createUserEndpoint)\n * async createUser(request: EndpointParams<typeof createUserEndpoint>) {\n * const existing = await this.userService.findByEmail(request.data.email)\n * if (existing) {\n * throw new ConflictException('User with this email already exists')\n * }\n * // ...\n * }\n * ```\n */\nexport class ConflictException extends HttpException {\n /**\n * Creates a new ConflictException.\n * \n * @param message - Error message or response object\n * @param error - Optional underlying error for logging\n */\n constructor(message: string | object, error?: Error) {\n super(409, message, error)\n }\n}\n","import type { ClassTypeWithInstance, ScopedContainer } from '@navios/di'\n\nimport { inject, Injectable, InjectionToken } from '@navios/di'\n\nimport type {\n AbstractExecutionContext,\n CanActivate,\n} from '../interfaces/index.mjs'\nimport type {\n ControllerMetadata,\n HandlerMetadata,\n ModuleMetadata,\n} from '../metadata/index.mjs'\n\nimport { HttpException } from '../exceptions/index.mjs'\nimport { Logger } from '../logger/index.mjs'\n\n@Injectable()\nexport class GuardRunnerService {\n private readonly logger = inject(Logger, {\n context: GuardRunnerService.name,\n })\n async runGuards(\n allGuards: Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >,\n executionContext: AbstractExecutionContext,\n context: ScopedContainer,\n ) {\n let canActivate = true\n for (const guard of Array.from(allGuards).reverse()) {\n const guardInstance = await context.get(\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 this.logger.error('Error running guard', error)\n executionContext.getReply().status(500).send({\n message: 'Internal server error',\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 moduleMetadata: ModuleMetadata,\n controllerMetadata: ControllerMetadata,\n endpoint: HandlerMetadata,\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 = endpoint.guards\n const controllerGuards = controllerMetadata.guards\n const moduleGuards = moduleMetadata.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 { ClassTypeWithInstance } from '@navios/di'\n\nimport { Container, inject, Injectable } from '@navios/di'\n\nimport type { NaviosModule } from '../interfaces/index.mjs'\nimport type { ModuleMetadata } from '../metadata/index.mjs'\n\nimport { Logger } from '../logger/index.mjs'\nimport { extractModuleMetadata } from '../metadata/index.mjs'\n\n@Injectable()\nexport class ModuleLoaderService {\n private logger = inject(Logger, {\n context: ModuleLoaderService.name,\n })\n protected container = inject(Container)\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 try {\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 this.container.get(module)\n if (instance.onModuleInit) {\n await instance.onModuleInit()\n }\n this.logger.debug(`Module ${moduleName} loaded`)\n this.loadedModules.set(moduleName, instance)\n } catch (error) {\n this.logger.error(`Error loading module ${moduleName}`, error)\n throw error\n }\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 dispose() {\n this.modulesMetadata.clear()\n this.loadedModules.clear()\n this.initialized = false\n }\n}\n","import type { ClassType } from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport type {\n ControllerMetadata,\n HandlerMetadata,\n ModuleMetadata,\n} from './metadata/index.mjs'\n\nimport {\n getControllerMetadata,\n getEndpointMetadata,\n getModuleMetadata,\n hasControllerMetadata,\n hasModuleMetadata,\n} from './metadata/index.mjs'\n\n/**\n * Type for a class attribute decorator without a value.\n * \n * Attributes are custom metadata decorators that can be applied to modules,\n * controllers, and endpoints.\n */\nexport type ClassAttribute = (() => <T>(\n target: T,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n) => T) & {\n token: symbol\n}\n\n/**\n * Type for a class attribute decorator with a validated value.\n * \n * @typeParam T - The Zod schema type for validation\n */\nexport type ClassSchemaAttribute<T extends ZodType> = ((\n value: z.input<T>,\n) => <T>(\n target: T,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n) => T) & {\n token: symbol\n schema: ZodType\n}\n\n/**\n * Factory for creating custom attribute decorators.\n * \n * Attributes allow you to add custom metadata to modules, controllers, and endpoints.\n * This is useful for cross-cutting concerns like rate limiting, caching, API versioning, etc.\n * \n * @example\n * ```typescript\n * // Create a simple boolean attribute\n * const Public = AttributeFactory.createAttribute(Symbol.for('Public'))\n * \n * // Use it as a decorator\n * @Controller()\n * @Public()\n * export class PublicController { }\n * \n * // Check if attribute exists\n * if (AttributeFactory.has(Public, controllerMetadata)) {\n * // Skip authentication\n * }\n * ```\n * \n * @example\n * ```typescript\n * // Create an attribute with a validated value\n * const RateLimit = AttributeFactory.createAttribute(\n * Symbol.for('RateLimit'),\n * z.object({ requests: z.number(), window: z.number() })\n * )\n * \n * // Use it with a value\n * @Endpoint(apiEndpoint)\n * @RateLimit({ requests: 100, window: 60000 })\n * async handler() { }\n * \n * // Get the value\n * const limit = AttributeFactory.get(RateLimit, endpointMetadata)\n * // limit is typed as { requests: number, window: number } | null\n * ```\n */\nexport class AttributeFactory {\n /**\n * Creates a simple attribute decorator without a value.\n * \n * @param token - A unique symbol to identify this attribute\n * @returns A decorator function that can be applied to classes or methods\n * \n * @example\n * ```typescript\n * const Public = AttributeFactory.createAttribute(Symbol.for('Public'))\n * \n * @Public()\n * @Controller()\n * export class PublicController { }\n * ```\n */\n static createAttribute(token: symbol): ClassAttribute\n /**\n * Creates an attribute decorator with a validated value.\n * \n * @param token - A unique symbol to identify this attribute\n * @param schema - A Zod schema to validate the attribute value\n * @returns A decorator function that accepts a value and can be applied to classes or methods\n * \n * @example\n * ```typescript\n * const RateLimit = AttributeFactory.createAttribute(\n * Symbol.for('RateLimit'),\n * z.object({ requests: z.number(), window: z.number() })\n * )\n * \n * @RateLimit({ requests: 100, window: 60000 })\n * @Endpoint(apiEndpoint)\n * async handler() { }\n * ```\n */\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 /**\n * Gets the value of an attribute from metadata.\n * \n * Returns `null` if the attribute is not present.\n * For simple attributes (without values), returns `true` if present.\n * \n * @param attribute - The attribute decorator\n * @param target - The metadata object (module, controller, or handler)\n * @returns The attribute value, `true` for simple attributes, or `null` if not found\n * \n * @example\n * ```typescript\n * const isPublic = AttributeFactory.get(Public, controllerMetadata)\n * // isPublic is true | null\n * \n * const rateLimit = AttributeFactory.get(RateLimit, endpointMetadata)\n * // rateLimit is { requests: number, window: number } | null\n * ```\n */\n static get(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): true | null\n static get<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): z.output<T> | null\n static get(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ) {\n return target.customAttributes.get(attribute.token) ?? null\n }\n\n /**\n * Gets all values of an attribute from metadata (useful when an attribute can appear multiple times).\n * \n * Returns `null` if the attribute is not present.\n * \n * @param attribute - The attribute decorator\n * @param target - The metadata object (module, controller, or handler)\n * @returns An array of attribute values, or `null` if not found\n * \n * @example\n * ```typescript\n * const tags = AttributeFactory.getAll(Tag, endpointMetadata)\n * // tags is string[] | null\n * ```\n */\n static getAll(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): Array<true> | null\n static getAll<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): Array<z.output<T>> | null\n static getAll(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\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 /**\n * Gets the last value of an attribute from an array of metadata objects.\n * \n * Searches from the end of the array backwards, useful for finding the most\n * specific attribute value (e.g., endpoint-level overrides module-level).\n * \n * @param attribute - The attribute decorator\n * @param target - An array of metadata objects (typically [module, controller, handler])\n * @returns The last attribute value found, or `null` if not found\n * \n * @example\n * ```typescript\n * // Check attribute hierarchy: endpoint -> controller -> module\n * const rateLimit = AttributeFactory.getLast(RateLimit, [\n * moduleMetadata,\n * controllerMetadata,\n * endpointMetadata\n * ])\n * ```\n */\n static getLast(\n attribute: ClassAttribute,\n target: (ModuleMetadata | ControllerMetadata | HandlerMetadata<any>)[],\n ): true | null\n static getLast<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: (ModuleMetadata | ControllerMetadata | HandlerMetadata<any>)[],\n ): z.output<T> | null\n static getLast(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: (ModuleMetadata | ControllerMetadata | HandlerMetadata<any>)[],\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 /**\n * Checks if an attribute is present on the metadata object.\n * \n * @param attribute - The attribute decorator\n * @param target - The metadata object (module, controller, or handler)\n * @returns `true` if the attribute is present, `false` otherwise\n * \n * @example\n * ```typescript\n * if (AttributeFactory.has(Public, controllerMetadata)) {\n * // Skip authentication\n * }\n * ```\n */\n static has(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): boolean\n static has<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): boolean\n static has(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ) {\n return target.customAttributes.has(attribute.token)\n }\n}\n","import type { AnyInjectableType, InjectionToken } from '@navios/di'\n\nimport { Injectable } from '@navios/di'\n\nexport interface NaviosEnvironmentOptions {\n // Future options can be added here\n httpTokens?: Map<InjectionToken<any, undefined>, AnyInjectableType>\n}\n\n@Injectable()\nexport class NaviosEnvironment {\n private httpTokens = new Map<\n InjectionToken<any, undefined>,\n AnyInjectableType\n >()\n\n setupHttpEnvironment(\n tokens: Map<InjectionToken<any, undefined>, AnyInjectableType>,\n ) {\n this.httpTokens = tokens\n }\n\n getHttpToken(token: InjectionToken<any, undefined>) {\n return this.httpTokens.get(token)\n }\n\n hasHttpSetup() {\n return this.httpTokens.size > 0\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { EndpointAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: EndpointAdapterToken,\n})\nexport class EndpointAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(EndpointAdapterToken)\n if (!service) {\n throw new Error('EndpointAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext } from '@navios/di'\n\nimport { Factory, inject, InjectionToken } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { HttpAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: HttpAdapterToken,\n})\nexport class HttpAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(HttpAdapterToken)\n if (!service) {\n throw new Error('HttpAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { MultipartAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: MultipartAdapterToken,\n})\nexport class MultipartAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(MultipartAdapterToken)\n if (!service) {\n throw new Error('MultipartAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject, InjectableScope } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { Request } from '../tokens/index.mjs'\n\n@Factory({\n token: Request,\n scope: InjectableScope.Request,\n})\nexport class RequestFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(Request)\n if (!service) {\n throw new Error('RequestToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject, InjectableScope } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { Reply } from '../tokens/index.mjs'\n\n@Factory({\n token: Reply,\n scope: InjectableScope.Request,\n})\nexport class ReplyFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(Reply)\n if (!service) {\n throw new Error('ReplyToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { StreamAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: StreamAdapterToken,\n})\nexport class StreamAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(StreamAdapterToken)\n if (!service) {\n throw new Error('StreamAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { XmlStreamAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: XmlStreamAdapterToken,\n})\nexport class XmlStreamAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(XmlStreamAdapterToken)\n if (!service) {\n throw new Error('XmlStreamAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { ClassTypeWithInstance } from '@navios/di'\n\nimport { Container, inject, Injectable } from '@navios/di'\n\nimport type {\n AbstractHttpAdapterInterface,\n AbstractHttpListenOptions,\n NaviosModule,\n PluginContext,\n PluginDefinition,\n} from './interfaces/index.mjs'\nimport type { LoggerService, LogLevel } from './logger/index.mjs'\nimport type { NaviosEnvironmentOptions } from './navios.environment.mjs'\n\nimport { HttpAdapterToken } from './index.mjs'\nimport { Logger } from './logger/index.mjs'\nimport { NaviosEnvironment } from './navios.environment.mjs'\nimport { ModuleLoaderService } from './services/index.mjs'\n\n/**\n * Options for configuring the Navios application context.\n * These options control dependency injection and logging behavior.\n */\nexport interface NaviosApplicationContextOptions {\n /**\n * Specifies the logger to use. Pass `false` to turn off logging.\n * \n * - `LoggerService` instance: Use a custom logger implementation\n * - `LogLevel[]`: Enable specific log levels (e.g., ['error', 'warn', 'log'])\n * - `false`: Disable logging completely\n */\n logger?: LoggerService | LogLevel[] | false\n\n /**\n * Specifies a custom container to use. Useful for testing.\n * If not provided, a new Container will be created.\n */\n container?: Container\n}\n\n/**\n * Complete options for creating a Navios application.\n * Extends NaviosApplicationContextOptions with adapter configuration.\n */\nexport interface NaviosApplicationOptions\n extends NaviosApplicationContextOptions {\n /**\n * HTTP adapter environment(s) to use for the application.\n * Can be a single adapter or an array of adapters.\n * \n * @example\n * ```typescript\n * adapter: defineFastifyEnvironment()\n * // or\n * adapter: [defineFastifyEnvironment(), defineBunEnvironment()]\n * ```\n */\n adapter: NaviosEnvironmentOptions | NaviosEnvironmentOptions[]\n}\n\n/**\n * Main application class for Navios.\n * \n * This class represents a Navios application instance and provides methods\n * for initializing, configuring, and managing the HTTP server.\n * \n * @example\n * ```typescript\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * })\n * \n * app.setGlobalPrefix('/api')\n * app.enableCors({ origin: ['http://localhost:3000'] })\n * await app.init()\n * await app.listen({ port: 3000, host: '0.0.0.0' })\n * ```\n */\n@Injectable()\nexport class NaviosApplication {\n private environment = inject(NaviosEnvironment)\n private moduleLoader = inject(ModuleLoaderService)\n private httpApplication: AbstractHttpAdapterInterface<any> | null = null\n private logger = inject(Logger, {\n context: NaviosApplication.name,\n })\n protected container = inject(Container)\n\n private appModule: ClassTypeWithInstance<NaviosModule> | null = null\n private options: NaviosApplicationOptions = {\n adapter: [],\n }\n private plugins: PluginDefinition<any>[] = []\n\n /**\n * Indicates whether the application has been initialized.\n * Set to `true` after `init()` completes successfully.\n */\n isInitialized = false\n\n /**\n * Sets up the application with the provided module and options.\n * This is called automatically by NaviosFactory.create().\n * \n * @param appModule - The root application module\n * @param options - Application configuration options\n * @internal\n */\n async setup(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: NaviosApplicationOptions = {\n adapter: [],\n },\n ) {\n this.appModule = appModule\n this.options = options\n if (this.environment.hasHttpSetup()) {\n this.httpApplication = await this.container.get(HttpAdapterToken)\n }\n }\n\n /**\n * Gets the dependency injection container used by this application.\n * \n * @returns The Container instance\n */\n getContainer() {\n return this.container\n }\n\n /**\n * Registers a plugin to be initialized after modules are loaded.\n *\n * Plugins are initialized in the order they are registered,\n * after all modules are loaded but before the server starts listening.\n *\n * @param definition - Plugin definition with options\n * @returns this for method chaining\n *\n * @example\n * ```typescript\n * import { defineOpenApiPlugin } from '@navios/openapi-fastify'\n *\n * app.usePlugin(defineOpenApiPlugin({\n * info: { title: 'My API', version: '1.0.0' },\n * }))\n * ```\n */\n usePlugin<TOptions>(definition: PluginDefinition<TOptions>): this {\n this.plugins.push(definition)\n return this\n }\n\n /**\n * Initializes the application.\n *\n * This method:\n * - Loads all modules and their dependencies\n * - Sets up the HTTP server if an adapter is configured\n * - Calls onModuleInit hooks on all modules\n * - Initializes registered plugins\n * - Marks the application as initialized\n *\n * Must be called before `listen()`.\n *\n * @throws Error if app module is not set\n *\n * @example\n * ```typescript\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * })\n * await app.init()\n * await app.listen({ port: 3000 })\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 if (this.environment.hasHttpSetup()) {\n await this.httpApplication?.setupHttpServer(this.options)\n }\n await this.initModules()\n await this.initPlugins()\n if (this.environment.hasHttpSetup()) {\n await this.httpApplication?.ready()\n }\n\n this.isInitialized = true\n this.logger.debug('Navios application initialized')\n }\n\n private async initModules() {\n const modules = this.moduleLoader.getAllModules()\n await this.httpApplication?.onModulesInit(modules)\n }\n\n private async initPlugins() {\n if (this.plugins.length === 0) return\n\n const context: PluginContext = {\n modules: this.moduleLoader.getAllModules(),\n server: this.httpApplication?.getServer() ?? null,\n container: this.container,\n globalPrefix: this.httpApplication?.getGlobalPrefix() ?? '',\n }\n\n for (const { plugin, options } of this.plugins) {\n this.logger.debug(`Initializing plugin: ${plugin.name}`)\n await plugin.register(context, options)\n }\n }\n\n /**\n * Enables CORS (Cross-Origin Resource Sharing) for the application.\n * \n * @param options - CORS configuration options (adapter-specific)\n * @throws Error if HTTP application is not set\n * \n * @example\n * ```typescript\n * app.enableCors({\n * origin: ['http://localhost:3000', 'https://example.com'],\n * methods: ['GET', 'POST', 'PUT', 'DELETE'],\n * credentials: true,\n * })\n * ```\n */\n enableCors(options: any) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n this.httpApplication.enableCors(options)\n }\n\n /**\n * Enables multipart/form-data support for file uploads.\n * \n * @param options - Multipart configuration options (adapter-specific)\n * @throws Error if HTTP application is not set\n * \n * @example\n * ```typescript\n * app.enableMultipart({\n * limits: {\n * fileSize: 1024 * 1024 * 10, // 10MB\n * },\n * })\n * ```\n */\n enableMultipart(options: any) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n this.httpApplication.enableMultipart(options)\n }\n\n /**\n * Sets a global prefix for all routes.\n * \n * @param prefix - The prefix to prepend to all route URLs (e.g., '/api')\n * @throws Error if HTTP application is not set\n * \n * @example\n * ```typescript\n * app.setGlobalPrefix('/api/v1')\n * // All routes will be prefixed with /api/v1\n * ```\n */\n setGlobalPrefix(prefix: string) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n this.httpApplication.setGlobalPrefix(prefix)\n }\n\n /**\n * Gets the underlying HTTP server instance.\n * \n * The type of the returned server depends on the adapter used:\n * - Fastify adapter: Returns FastifyInstance\n * - Bun adapter: Returns Bun.Server\n * \n * @returns The HTTP server instance\n * @throws Error if HTTP application is not set\n * \n * @example\n * ```typescript\n * const server = app.getServer()\n * // Use adapter-specific server methods\n * ```\n */\n getServer() {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n return this.httpApplication.getServer()\n }\n\n /**\n * Starts the HTTP server and begins listening for requests.\n * \n * @param options - Listen options (port, host, etc.)\n * @throws Error if HTTP application is not set\n * \n * @example\n * ```typescript\n * await app.listen({ port: 3000, host: '0.0.0.0' })\n * ```\n */\n async listen(options: AbstractHttpListenOptions) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n await this.httpApplication.listen(options)\n }\n\n /**\n * Disposes of application resources.\n * \n * Cleans up the HTTP server and module loader.\n * This method is called automatically by `close()`.\n */\n async dispose() {\n if (this.httpApplication) {\n await this.httpApplication.dispose()\n }\n if (this.moduleLoader) {\n this.moduleLoader.dispose()\n }\n }\n\n /**\n * Closes the application and cleans up all resources.\n * \n * This is an alias for `dispose()`.\n * \n * @example\n * ```typescript\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await app.close()\n * process.exit(0)\n * })\n * ```\n */\n async close() {\n await this.dispose()\n }\n}\n","import type {\n AnyInjectableType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport { Container, InjectableScope, InjectableType } from '@navios/di'\n\nimport type { NaviosModule } from './interfaces/index.mjs'\nimport type {\n NaviosApplicationContextOptions,\n NaviosApplicationOptions,\n} from './navios.application.mjs'\n\nimport { ConsoleLogger, isNil, LoggerOutput } from './logger/index.mjs'\nimport { NaviosApplication } from './navios.application.mjs'\nimport { NaviosEnvironment } from './navios.environment.mjs'\n\n/**\n * Factory class for creating and configuring Navios applications.\n * \n * This is the main entry point for bootstrapping a Navios application.\n * It handles dependency injection container setup, adapter registration,\n * and logger configuration.\n * \n * @example\n * ```typescript\n * import { NaviosFactory } from '@navios/core'\n * import { defineFastifyEnvironment } from '@navios/adapter-fastify'\n * \n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * logger: ['log', 'error', 'warn'],\n * })\n * \n * await app.init()\n * await app.listen({ port: 3000 })\n * ```\n */\nexport class NaviosFactory {\n /**\n * Creates a new Navios application instance.\n * \n * This method sets up the dependency injection container, registers the HTTP adapter,\n * configures logging, and initializes the application with the provided module.\n * \n * @param appModule - The root application module class decorated with @Module()\n * @param options - Configuration options for the application\n * @param options.adapter - HTTP adapter environment (required for HTTP server functionality)\n * @param options.logger - Logger configuration. Can be:\n * - A LoggerService instance for custom logging\n * - An array of LogLevel strings to enable specific log levels\n * - `false` to disable logging\n * @param options.container - Optional custom dependency injection container (useful for testing)\n * @returns A configured NaviosApplication instance ready to be initialized\n * \n * @example\n * ```typescript\n * // Basic setup with Fastify adapter\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * })\n * \n * // With custom logger configuration\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * logger: ['error', 'warn', 'log'],\n * })\n * \n * // With custom container for testing\n * const container = new Container()\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * container,\n * })\n * ```\n */\n static async create(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: NaviosApplicationOptions = {\n adapter: [],\n },\n ) {\n const container = options.container ?? new Container()\n await this.registerLoggerConfiguration(container, options)\n const adapters = Array.isArray(options.adapter)\n ? options.adapter\n : [options.adapter]\n for (const adapter of adapters) {\n await this.registerEnvironment(container, adapter)\n }\n const app = await container.get(NaviosApplication)\n await app.setup(appModule, options)\n return app\n }\n\n private static async registerEnvironment(\n container: Container,\n environment: {\n httpTokens?: Map<InjectionToken<any, undefined>, AnyInjectableType>\n } = {},\n ) {\n const naviosEnvironment = await container.get(NaviosEnvironment)\n const { httpTokens } = environment\n if (httpTokens) {\n naviosEnvironment.setupHttpEnvironment(httpTokens)\n }\n }\n\n private static async registerLoggerConfiguration(\n container: Container,\n options: NaviosApplicationContextOptions,\n ) {\n const { logger } = options\n if (Array.isArray(logger) || isNil(logger)) {\n const loggerInstance = (await container.get(\n LoggerOutput,\n )) as ConsoleLogger\n loggerInstance?.setup({\n logLevels: logger,\n })\n }\n if ((logger as boolean) !== true && !isNil(logger)) {\n container\n .getServiceLocator()\n .getManager()\n .storeCreatedHolder(\n LoggerOutput.toString(),\n logger,\n InjectableType.Class,\n InjectableScope.Singleton,\n )\n }\n }\n}\n","import { $ as envInt, A as loggerOptionsSchema, B as isObject, C as ConfigServiceOptionsSchema, D as _ConsoleLogger, E as _LoggerInstance, F as isConstructor, G as normalizePath, H as isString, I as isEmpty, J as filterLogLevels, K as stripEndSlash, L as isFunction, M as requestIdStore, N as runWithRequestId, O as Logger, P as addLeadingSlash, Q as yellow, R as isNil, S as provideConfig, T as _ConfigService, U as isSymbol, V as isPlainObject, W as isUndefined, X as LOG_LEVELS, Y as isLogLevel, Z as clc, _ as ForbiddenException, a as _ReplyFactory, b as ConfigProviderOptions, c as _HttpAdapterFactory, d as _ModuleLoaderService, et as envString, f as _GuardRunnerService, g as InternalServerErrorException, h as NotFoundException, i as _StreamAdapterFactory, j as getRequestId, k as LoggerOutput, l as _EndpointAdapterFactory, m as UnauthorizedException, n as _NaviosApplication, o as _RequestFactory, p as ConflictException, q as isLogLevelEnabled, r as _XmlStreamAdapterFactory, s as _MultipartAdapterFactory, t as NaviosFactory, u as AttributeFactory, v as BadRequestException, w as ConfigServiceToken, x as EnvConfigProvider, y as HttpException, z as isNumber } from \"./src-DpPBxmjz.mjs\";\nimport { C as extractControllerMetadata, D as getAllEndpointMetadata, E as EndpointMetadataKey, O as getEndpointMetadata, S as ControllerMetadataKey, T as hasControllerMetadata, _ as Controller, a as HttpCode, b as getModuleMetadata, c as XmlStreamAdapterToken, d as Reply, f as MultipartAdapterToken, g as EndpointAdapterToken, h as ExecutionContextInjectionToken, i as Module, l as StreamAdapterToken, m as ExecutionContext, n as Stream, o as Header, p as HttpAdapterToken, r as Multipart, s as Endpoint, t as UseGuards, u as Request, v as ModuleMetadataKey, w as getControllerMetadata, x as hasModuleMetadata, y as extractModuleMetadata } from \"./use-guards.decorator-kZ3lNK8v.mjs\";\n\nexport * from \"@navios/di\"\n\nexport { AttributeFactory, BadRequestException, ConfigProviderOptions, _ConfigService as ConfigService, ConfigServiceOptionsSchema, ConfigServiceToken, ConflictException, _ConsoleLogger as ConsoleLogger, Controller, ControllerMetadataKey, Endpoint, _EndpointAdapterFactory as EndpointAdapterFactory, EndpointAdapterToken, EndpointMetadataKey, EnvConfigProvider, ExecutionContext, ExecutionContextInjectionToken, ForbiddenException, _GuardRunnerService as GuardRunnerService, Header, _HttpAdapterFactory as HttpAdapterFactory, HttpAdapterToken, HttpCode, HttpException, InternalServerErrorException, LOG_LEVELS, Logger, _LoggerInstance as LoggerInstance, LoggerOutput, Module, _ModuleLoaderService as ModuleLoaderService, ModuleMetadataKey, Multipart, _MultipartAdapterFactory as MultipartAdapterFactory, MultipartAdapterToken, _NaviosApplication as NaviosApplication, NaviosFactory, NotFoundException, Reply, _ReplyFactory as ReplyFactory, Request, _RequestFactory as RequestFactory, Stream, _StreamAdapterFactory as StreamAdapterFactory, StreamAdapterToken, UnauthorizedException, UseGuards, _XmlStreamAdapterFactory as XmlStreamAdapterFactory, XmlStreamAdapterToken, addLeadingSlash, clc, envInt, envString, extractControllerMetadata, extractModuleMetadata, filterLogLevels, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getModuleMetadata, getRequestId, hasControllerMetadata, hasModuleMetadata, isConstructor, isEmpty, isFunction, isLogLevel, isLogLevelEnabled, isNil, isNumber, isObject, isPlainObject, isString, isSymbol, isUndefined, loggerOptionsSchema, normalizePath, provideConfig, requestIdStore, runWithRequestId, stripEndSlash, yellow };","import type { CommandMetadata } from '../metadata/command.metadata.mjs'\n\n/**\n * Execution context for a command execution.\n *\n * Provides access to command metadata, path, and validated options during command execution.\n * This context is automatically injected and available via the `CommandExecutionContext` token.\n *\n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/di'\n * import { CommandExecutionContext } from '@navios/commander'\n *\n * @Injectable()\n * class CommandLogger {\n * private ctx = inject(CommandExecutionContext)\n *\n * log() {\n * console.log('Command:', this.ctx.getCommandPath())\n * console.log('Options:', this.ctx.getOptions())\n * }\n * }\n * ```\n */\nexport class CommanderExecutionContext {\n /**\n * @internal\n * Creates a new execution context.\n */\n constructor(\n private readonly command: CommandMetadata,\n private readonly commandPath: string,\n private readonly options: any,\n ) {}\n\n /**\n * Gets the command metadata.\n *\n * @returns The command metadata including path and options schema\n */\n getCommand(): CommandMetadata {\n return this.command\n }\n\n /**\n * Gets the command path that was invoked.\n *\n * @returns The command path (e.g., 'greet', 'user:create')\n */\n getCommandPath(): string {\n return this.commandPath\n }\n\n /**\n * Gets the validated command options.\n *\n * Options are validated against the command's Zod schema if one was provided.\n *\n * @returns The validated options object\n */\n getOptions(): any {\n return this.options\n }\n}\n","import type { ClassType } from '@navios/core'\nimport type { ZodObject } from 'zod'\n\n/**\n * @internal\n * Symbol key used to store command metadata on classes.\n */\nexport const CommandMetadataKey = Symbol('CommandMetadataKey')\n\n/**\n * Metadata associated with a command.\n *\n * @public\n */\nexport interface CommandMetadata {\n /**\n * The command path (e.g., 'greet', 'user:create').\n */\n path: string\n /**\n * Optional Zod schema for validating command options.\n */\n optionsSchema?: ZodObject\n /**\n * Map of custom attributes that can be attached to the command.\n */\n customAttributes: Map<string | symbol, any>\n}\n\n/**\n * Gets or creates command metadata for a class.\n *\n * @internal\n * @param target - The command class\n * @param context - The decorator context\n * @param path - The command path\n * @param optionsSchema - Optional Zod schema\n * @returns The command metadata\n */\nexport function getCommandMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n path: string,\n optionsSchema?: ZodObject,\n): CommandMetadata {\n if (context.metadata) {\n const metadata = context.metadata[CommandMetadataKey] as\n | CommandMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const newMetadata: CommandMetadata = {\n path,\n optionsSchema,\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[CommandMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[CommandMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios Commander] Wrong environment.')\n}\n\n/**\n * Extracts command metadata from a class.\n *\n * @param target - The command class\n * @returns The command metadata\n * @throws {Error} If the class is not decorated with @Command\n *\n * @example\n * ```typescript\n * const metadata = extractCommandMetadata(GreetCommand)\n * console.log(metadata.path) // 'greet'\n * ```\n */\nexport function extractCommandMetadata(target: ClassType): CommandMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CommandMetadataKey] as CommandMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios Commander] Command metadata not found. Make sure to use @Command decorator.',\n )\n }\n return metadata\n}\n\n/**\n * Checks if a class has command metadata.\n *\n * @param target - The class to check\n * @returns `true` if the class is decorated with @Command, `false` otherwise\n */\nexport function hasCommandMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CommandMetadataKey] as CommandMetadata | undefined\n return !!metadata\n}\n","import type { ClassType } from '@navios/core'\n\n/**\n * @internal\n * Symbol key used to store CLI module metadata on classes.\n */\nexport const CliModuleMetadataKey = Symbol('CliModuleMetadataKey')\n\n/**\n * Metadata associated with a CLI module.\n *\n * @public\n */\nexport interface CliModuleMetadata {\n /**\n * Set of command classes registered in this module.\n */\n commands: Set<ClassType>\n /**\n * Set of other modules imported by this module.\n */\n imports: Set<ClassType>\n /**\n * Map of custom attributes that can be attached to the module.\n */\n customAttributes: Map<string | symbol, any>\n}\n\n/**\n * Gets or creates CLI module metadata for a class.\n *\n * @internal\n * @param target - The module class\n * @param context - The decorator context\n * @returns The module metadata\n */\nexport function getCliModuleMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): CliModuleMetadata {\n if (context.metadata) {\n const metadata = context.metadata[CliModuleMetadataKey] as\n | CliModuleMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const newMetadata: CliModuleMetadata = {\n commands: new Set<ClassType>(),\n imports: new Set<ClassType>(),\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[CliModuleMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[CliModuleMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios Commander] Wrong environment.')\n}\n\n/**\n * Extracts CLI module metadata from a class.\n *\n * @param target - The module class\n * @returns The module metadata\n * @throws {Error} If the class is not decorated with @CliModule\n *\n * @example\n * ```typescript\n * const metadata = extractCliModuleMetadata(AppModule)\n * console.log(metadata.commands.size) // Number of commands\n * ```\n */\nexport function extractCliModuleMetadata(target: ClassType): CliModuleMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CliModuleMetadataKey] as CliModuleMetadata | undefined\n if (!metadata) {\n throw new Error(\n `[Navios Commander] Module metadata not found for ${target.name}. Make sure to use @CliModule decorator.`,\n )\n }\n return metadata\n}\n\n/**\n * Checks if a class has CLI module metadata.\n *\n * @param target - The class to check\n * @returns `true` if the class is decorated with @CliModule, `false` otherwise\n */\nexport function hasCliModuleMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n return !!target[CliModuleMetadataKey]\n}\n","import type { ClassTypeWithInstance, NaviosModule } from '@navios/core'\n\nimport { Container, inject, Injectable } from '@navios/core'\n\nimport type { CommandHandler } from '../interfaces/index.mjs'\nimport type { CliModuleMetadata, CommandMetadata } from '../metadata/index.mjs'\n\nimport {\n extractCliModuleMetadata,\n extractCommandMetadata,\n} from '../metadata/index.mjs'\n\n/**\n * Command class with its associated metadata.\n *\n * @public\n */\nexport interface CommandWithMetadata {\n /**\n * The command class constructor.\n */\n class: ClassTypeWithInstance<CommandHandler>\n /**\n * The command metadata including path and options schema.\n */\n metadata: CommandMetadata\n}\n\n/**\n * Service for loading and managing CLI modules and commands.\n *\n * Handles module traversal, command registration, and metadata collection.\n * This service is used internally by CommanderApplication.\n *\n * @public\n */\n@Injectable()\nexport class CliModuleLoaderService {\n protected container = inject(Container)\n private modulesMetadata: Map<string, CliModuleMetadata> = new Map()\n private loadedModules: Map<string, any> = new Map()\n private commandsMetadata: Map<string, CommandWithMetadata> = new Map()\n private initialized = false\n\n /**\n * Loads all modules starting from the root app module.\n *\n * Traverses the module tree, loads imported modules, and collects command metadata.\n *\n * @param appModule - The root CLI module\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?: CliModuleMetadata,\n ) {\n const metadata = extractCliModuleMetadata(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\n // Collect command metadata during module loading\n for (const command of metadata.commands) {\n const commandMetadata = extractCommandMetadata(command)\n this.commandsMetadata.set(commandMetadata.path, {\n class: command,\n metadata: commandMetadata,\n })\n }\n\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 this.container.get(module)\n if (instance.onModuleInit) {\n await instance.onModuleInit()\n }\n this.loadedModules.set(moduleName, instance)\n }\n\n private mergeMetadata(\n metadata: CliModuleMetadata,\n parentMetadata: CliModuleMetadata,\n ): void {\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\n /**\n * Gets all loaded module metadata.\n *\n * @returns Map of module names to their metadata\n */\n getAllModules(): Map<string, CliModuleMetadata> {\n return this.modulesMetadata\n }\n\n /**\n * Gets all command classes indexed by command class name.\n *\n * @returns Map of command class names to command classes\n */\n getAllCommands(): Map<string, ClassTypeWithInstance<any>> {\n const commands = new Map<string, ClassTypeWithInstance<any>>()\n for (const metadata of this.modulesMetadata.values()) {\n for (const command of metadata.commands) {\n commands.set(command.name, command)\n }\n }\n return commands\n }\n\n /**\n * Get all commands with their metadata, indexed by command path.\n * This is populated during loadModules, so path information is available\n * before parsing CLI argv.\n */\n getAllCommandsWithMetadata(): Map<string, CommandWithMetadata> {\n return this.commandsMetadata\n }\n\n /**\n * Get a command by its path, with metadata already extracted.\n * Returns undefined if command is not found.\n */\n getCommandByPath(path: string): CommandWithMetadata | undefined {\n return this.commandsMetadata.get(path)\n }\n\n /**\n * Disposes of all loaded modules and commands, clearing internal state.\n */\n dispose() {\n this.modulesMetadata.clear()\n this.loadedModules.clear()\n this.commandsMetadata.clear()\n this.initialized = false\n }\n}\n","import type { ZodObject, ZodType } from 'zod'\n\nimport { Injectable } from '@navios/core'\n\n/**\n * Result of parsing command-line arguments.\n *\n * @public\n */\nexport interface ParsedCliArgs {\n /**\n * The command path (e.g., 'greet', 'user:create').\n * Multi-word commands are joined with spaces.\n */\n command: string\n /**\n * Parsed options as key-value pairs.\n * Keys are converted from kebab-case to camelCase.\n */\n options: Record<string, any>\n /**\n * Positional arguments that don't match any option flags.\n */\n positionals: string[]\n}\n\n/**\n * Service for parsing command-line arguments.\n *\n * Handles parsing of various CLI argument formats including:\n * - Long options: `--key value` or `--key=value`\n * - Short options: `-k value` or `-abc` (multiple flags)\n * - Boolean flags\n * - Array options\n * - Positional arguments\n *\n * @public\n */\n@Injectable()\nexport class CliParserService {\n /**\n * Parses command-line arguments from process.argv\n * Commands can be multi-word (e.g., 'db migrate', 'cache clear')\n * Expected format: node script.js command [subcommand...] --flag value --boolean-flag positional1 positional2\n *\n * @param argv - Array of command-line arguments (typically process.argv)\n * @param optionsSchema - Optional Zod schema to determine boolean flags and option types\n * @returns Parsed command (space-separated if multi-word), options, and positional arguments\n */\n parse(argv: string[], optionsSchema?: ZodObject): ParsedCliArgs {\n // Skip first two args (node and script path)\n const args = argv.slice(2)\n\n if (args.length === 0) {\n throw new Error('[Navios Commander] No command provided')\n }\n\n // Extract boolean and array field names from schema for accurate parsing\n const booleanFields = optionsSchema\n ? this.extractBooleanFields(optionsSchema)\n : new Set<string>()\n const arrayFields = optionsSchema\n ? this.extractArrayFields(optionsSchema)\n : new Set<string>()\n\n // Collect command words until we hit an argument that starts with '-' or '--'\n const commandParts: string[] = []\n let i = 0\n while (i < args.length && !args[i].startsWith('-')) {\n commandParts.push(args[i])\n i++\n }\n\n if (commandParts.length === 0) {\n throw new Error('[Navios Commander] No command provided')\n }\n\n const command = commandParts.join(' ')\n const options: Record<string, any> = {}\n const positionals: string[] = []\n while (i < args.length) {\n const arg = args[i]\n\n if (arg.startsWith('--')) {\n // Long option format: --key=value or --key value\n const key = arg.slice(2)\n const equalIndex = key.indexOf('=')\n\n if (equalIndex !== -1) {\n // Format: --key=value\n const optionName = key.slice(0, equalIndex)\n const optionValue = key.slice(equalIndex + 1)\n const camelCaseKey = this.camelCase(optionName)\n const isArray =\n arrayFields.has(camelCaseKey) || arrayFields.has(optionName)\n\n if (isArray) {\n // For array fields, accumulate values\n if (!options[camelCaseKey]) {\n options[camelCaseKey] = []\n }\n options[camelCaseKey].push(this.parseValue(optionValue))\n } else {\n options[camelCaseKey] = this.parseValue(optionValue)\n }\n i++\n } else {\n // Format: --key value or --boolean-flag\n const camelCaseKey = this.camelCase(key)\n const isBoolean =\n booleanFields.has(camelCaseKey) || booleanFields.has(key)\n const isArray = arrayFields.has(camelCaseKey) || arrayFields.has(key)\n const nextArg = args[i + 1]\n\n if (isBoolean) {\n // Known boolean flag from schema\n options[camelCaseKey] = true\n i++\n } else if (isArray && nextArg && !nextArg.startsWith('-')) {\n // Known array field from schema - accumulate values\n if (!options[camelCaseKey]) {\n options[camelCaseKey] = []\n }\n options[camelCaseKey].push(this.parseValue(nextArg))\n i += 2\n } else if (nextArg && !nextArg.startsWith('-')) {\n // Has a value\n options[camelCaseKey] = this.parseValue(nextArg)\n i += 2\n } else {\n // Assume boolean flag\n options[camelCaseKey] = true\n i++\n }\n }\n } else if (arg.startsWith('-') && arg.length > 1 && arg !== '-') {\n // Short option format: -k value or -abc (multiple flags)\n const flags = arg.slice(1)\n\n if (flags.length === 1) {\n // Single short flag: -k value or -k\n const isBoolean = booleanFields.has(flags)\n const isArray = arrayFields.has(flags)\n const nextArg = args[i + 1]\n\n if (isBoolean) {\n // Known boolean flag from schema\n options[flags] = true\n i++\n } else if (isArray && nextArg && !nextArg.startsWith('-')) {\n // Known array field from schema - accumulate values\n if (!options[flags]) {\n options[flags] = []\n }\n options[flags].push(this.parseValue(nextArg))\n i += 2\n } else if (nextArg && !nextArg.startsWith('-')) {\n options[flags] = this.parseValue(nextArg)\n i += 2\n } else {\n options[flags] = true\n i++\n }\n } else {\n // Multiple short flags: -abc -> {a: true, b: true, c: true}\n for (const flag of flags) {\n options[flag] = true\n }\n i++\n }\n } else {\n // Positional argument\n positionals.push(arg)\n i++\n }\n }\n\n return {\n command,\n options,\n positionals,\n }\n }\n\n /**\n * Converts kebab-case to camelCase\n */\n private camelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())\n }\n\n /**\n * Attempts to parse string values into appropriate types\n */\n private parseValue(value: string): any {\n // Check for boolean\n if (value === 'true') return true\n if (value === 'false') return false\n\n // Check for null/undefined\n if (value === 'null') return null\n if (value === 'undefined') return undefined\n\n // Check for number\n if (/^-?\\d+$/.test(value)) {\n return parseInt(value, 10)\n }\n if (/^-?\\d+\\.\\d+$/.test(value)) {\n return parseFloat(value)\n }\n\n // Check for JSON\n if (\n (value.startsWith('{') && value.endsWith('}')) ||\n (value.startsWith('[') && value.endsWith(']'))\n ) {\n try {\n return JSON.parse(value)\n } catch {\n // If parsing fails, return as string\n return value\n }\n }\n\n // Return as string\n return value\n }\n\n /**\n * Extracts boolean field names from a Zod schema\n * Handles ZodObject, ZodOptional, and ZodDefault wrappers\n */\n private extractBooleanFields(schema: ZodObject): Set<string> {\n const booleanFields = new Set<string>()\n\n try {\n // Check if schema has _def.typeName (Zod schema structure)\n const typeName = schema.def.type\n\n if (typeName === 'object') {\n // Extract shape from ZodObject\n const shape = schema.def.shape\n\n if (shape && typeof shape === 'object') {\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (this.isSchemaBoolean(fieldSchema as any)) {\n booleanFields.add(key)\n }\n }\n }\n }\n } catch {\n // Silently fail if schema introspection fails\n }\n\n return booleanFields\n }\n\n /**\n * Extracts array field names from a Zod schema\n * Handles ZodObject, ZodOptional, and ZodDefault wrappers\n */\n private extractArrayFields(schema: ZodObject): Set<string> {\n const arrayFields = new Set<string>()\n\n try {\n const typeName = schema.def.type\n\n if (typeName === 'object') {\n const shape = schema.def.shape\n\n if (shape && typeof shape === 'object') {\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (this.isSchemaArray(fieldSchema as any)) {\n arrayFields.add(key)\n }\n }\n }\n }\n } catch {\n // Silently fail if schema introspection fails\n }\n\n return arrayFields\n }\n\n /**\n * Checks if a Zod schema represents a boolean type\n * Unwraps ZodOptional and ZodDefault\n */\n private isSchemaBoolean(schema: ZodType): boolean {\n try {\n let currentSchema = schema\n const typeName = currentSchema.def.type\n\n // Unwrap ZodOptional and ZodDefault\n if (typeName === 'optional' || typeName === 'default') {\n currentSchema = (currentSchema as any)?._def?.innerType || currentSchema\n }\n\n const innerTypeName = currentSchema.def.type\n return innerTypeName === 'boolean'\n } catch {\n return false\n }\n }\n\n /**\n * Checks if a Zod schema represents an array type\n * Unwraps ZodOptional and ZodDefault\n */\n private isSchemaArray(schema: ZodType): boolean {\n try {\n let currentSchema = schema\n const typeName = currentSchema.def.type\n\n // Unwrap ZodOptional and ZodDefault\n if (typeName === 'optional' || typeName === 'default') {\n currentSchema = (currentSchema as any)?._def?.innerType || currentSchema\n }\n\n const innerTypeName = currentSchema.def.type\n return innerTypeName === 'array'\n } catch {\n return false\n }\n }\n\n /**\n * Formats help text listing all available commands.\n *\n * @param commands - Array of command objects with path and class\n * @returns Formatted string listing all commands\n */\n formatCommandList(commands: Array<{ path: string; class: any }>): string {\n const lines = ['Available commands:', '']\n for (const { path } of commands) {\n lines.push(` ${path}`)\n }\n return lines.join('\\n')\n }\n}\n","import { InjectionToken } from '@navios/core'\n\nimport type { CommanderExecutionContext } from '../interfaces/index.mjs'\n\nconst CommandExecutionContextInjectionToken =\n 'CommanderExecutionContextInjectionToken'\n\n/**\n * Injection token for accessing the current command execution context.\n *\n * Use this token with `inject()` to access the `CommanderExecutionContext` in services\n * that need information about the currently executing command.\n *\n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/di'\n * import { CommandExecutionContext } from '@navios/commander'\n *\n * @Injectable()\n * class MyService {\n * private ctx = inject(CommandExecutionContext)\n *\n * doSomething() {\n * const commandPath = this.ctx.getCommandPath()\n * const options = this.ctx.getOptions()\n * // Use context information...\n * }\n * }\n * ```\n */\nexport const CommandExecutionContext =\n InjectionToken.create<CommanderExecutionContext>(\n CommandExecutionContextInjectionToken,\n )\n","import type {\n ClassTypeWithInstance,\n InjectionToken,\n NaviosModule,\n} from '@navios/core'\n\nimport { Container, inject, Injectable } from '@navios/core'\n\nimport type { CommandHandler } from './interfaces/index.mjs'\n\nimport { CommanderExecutionContext } from './interfaces/index.mjs'\nimport { CliModuleLoaderService, CliParserService } from './services/index.mjs'\nimport { CommandExecutionContext } from './tokens/index.mjs'\n\n/**\n * Configuration options for CommanderApplication.\n *\n * @public\n */\nexport interface CommanderApplicationOptions {}\n\n/**\n * Main application class for managing CLI command execution.\n *\n * This class handles module loading, command registration, and command execution.\n * It provides both programmatic and CLI-based command execution capabilities.\n *\n * @example\n * ```typescript\n * const app = await CommanderFactory.create(AppModule)\n * await app.init()\n * await app.run(process.argv)\n * ```\n */\n@Injectable()\nexport class CommanderApplication {\n private moduleLoader = inject(CliModuleLoaderService)\n private cliParser = inject(CliParserService)\n protected container = inject(Container)\n\n private appModule: ClassTypeWithInstance<NaviosModule> | null = null\n private options: CommanderApplicationOptions = {}\n\n /**\n * Indicates whether the application has been initialized.\n * Set to `true` after `init()` is called successfully.\n */\n isInitialized = false\n\n /**\n * @internal\n * Sets up the application with the provided module and options.\n * This is called automatically by CommanderFactory.create().\n */\n async setup(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: CommanderApplicationOptions = {},\n ) {\n this.appModule = appModule\n this.options = options\n }\n\n /**\n * Gets the dependency injection container used by this application.\n *\n * @returns The Container instance\n *\n * @example\n * ```typescript\n * const container = app.getContainer()\n * const service = await container.get(MyService)\n * ```\n */\n getContainer() {\n return this.container\n }\n\n /**\n * Initializes the application by loading all modules and registering commands.\n *\n * This method must be called before executing commands or running the CLI.\n * It traverses the module tree, loads all imported modules, and collects command metadata.\n *\n * @throws {Error} If the app module is not set (setup() was not called)\n *\n * @example\n * ```typescript\n * const app = await CommanderFactory.create(AppModule)\n * await app.init() // Must be called before run() or executeCommand()\n * ```\n */\n async init() {\n if (!this.appModule) {\n throw new Error(\n '[Navios Commander] App module is not set. Call setup() first.',\n )\n }\n await this.moduleLoader.loadModules(this.appModule)\n this.isInitialized = true\n }\n\n /**\n * Executes a command programmatically with the provided options.\n *\n * This method is useful for testing, automation, or programmatic workflows.\n * The options will be validated against the command's Zod schema if one is provided.\n *\n * @param commandPath - The command path (e.g., 'greet', 'user:create')\n * @param options - The command options object (will be validated if schema exists)\n * @throws {Error} If the application is not initialized\n * @throws {Error} If the command is not found\n * @throws {Error} If the command does not implement the execute method\n * @throws {ZodError} If options validation fails\n *\n * @example\n * ```typescript\n * await app.executeCommand('greet', {\n * name: 'World',\n * greeting: 'Hi'\n * })\n * ```\n */\n async executeCommand(commandPath: string, options: any = {}) {\n if (!this.isInitialized) {\n throw new Error(\n '[Navios Commander] Application is not initialized. Call init() first.',\n )\n }\n\n // Use pre-collected command metadata from module loading\n const commandWithMetadata = this.moduleLoader.getCommandByPath(commandPath)\n\n if (!commandWithMetadata) {\n throw new Error(`[Navios Commander] Command not found: ${commandPath}`)\n }\n\n const { class: commandClass, metadata } = commandWithMetadata\n\n // Validate options with zod schema if provided\n let validatedOptions = options\n if (metadata.optionsSchema) {\n validatedOptions = metadata.optionsSchema.parse(options)\n }\n\n // Create execution context and provide it to the container\n const executionContext = new CommanderExecutionContext(\n metadata,\n commandPath,\n validatedOptions,\n )\n\n // Generate a unique request ID for this command execution\n const requestId = `cmd-${Date.now()}-${Math.random().toString(36).substring(7)}`\n\n // Begin request context and add ExecutionContext\n const scopeContainer = this.container.beginRequest(requestId)\n scopeContainer.addInstance(CommandExecutionContext, executionContext)\n\n try {\n // Get command instance and execute\n const commandInstance = await scopeContainer.get<CommandHandler>(\n commandClass as unknown as InjectionToken<CommandHandler>,\n )\n\n if (!commandInstance.execute) {\n throw new Error(\n `[Navios Commander] Command ${commandPath} does not implement execute method`,\n )\n }\n\n await commandInstance.execute(validatedOptions)\n } finally {\n // Clean up request context\n await scopeContainer.endRequest()\n }\n }\n\n /**\n * Gets all registered commands with their paths and class references.\n *\n * @returns An array of objects containing the command path and class\n *\n * @example\n * ```typescript\n * const commands = app.getAllCommands()\n * commands.forEach(({ path }) => {\n * console.log(`Available: ${path}`)\n * })\n * ```\n */\n getAllCommands() {\n // Use pre-collected command metadata from module loading\n const commandsMap = this.moduleLoader.getAllCommandsWithMetadata()\n const commandsWithMetadata: Array<{\n path: string\n class: ClassTypeWithInstance<any>\n }> = []\n\n for (const [, { class: cmd, metadata }] of commandsMap) {\n commandsWithMetadata.push({\n path: metadata.path,\n class: cmd,\n })\n }\n\n return commandsWithMetadata\n }\n\n /**\n * Runs the CLI application by parsing command-line arguments and executing the appropriate command.\n *\n * This is the main entry point for CLI usage. It parses `argv`, validates options,\n * and executes the matching command. Supports help command (`help`, `--help`, `-h`)\n * which displays all available commands.\n *\n * @param argv - Command-line arguments array (defaults to `process.argv`)\n * @throws {Error} If the application is not initialized\n * @throws {Error} If no command is provided\n * @throws {Error} If the command is not found\n * @throws {ZodError} If options validation fails\n *\n * @example\n * ```typescript\n * // Parse and execute from process.argv\n * await app.run()\n *\n * // Or provide custom arguments\n * await app.run(['node', 'cli.js', 'greet', '--name', 'World'])\n * ```\n */\n async run(argv: string[] = process.argv) {\n if (!this.isInitialized) {\n throw new Error(\n '[Navios Commander] Application is not initialized. Call init() first.',\n )\n }\n\n try {\n // First, try to extract the command path to get its schema\n // We need to do a preliminary parse to find the command\n const preliminaryParse = this.cliParser.parse(argv)\n const commandWithMetadata = this.moduleLoader.getCommandByPath(\n preliminaryParse.command,\n )\n\n // Re-parse with schema if available\n const parsed = commandWithMetadata?.metadata.optionsSchema\n ? this.cliParser.parse(argv, commandWithMetadata.metadata.optionsSchema)\n : preliminaryParse\n\n // Handle special commands\n if (\n parsed.command === 'help' ||\n parsed.options.help ||\n parsed.options.h\n ) {\n const commands = this.getAllCommands()\n console.log(this.cliParser.formatCommandList(commands))\n return\n }\n\n // Execute the command\n await this.executeCommand(parsed.command, parsed.options)\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error: ${error.message}`)\n\n // Show available commands on error\n if (error.message.includes('Command not found')) {\n console.log(\n '\\n' + this.cliParser.formatCommandList(this.getAllCommands()),\n )\n }\n }\n throw error\n }\n }\n\n /**\n * @internal\n * Disposes of resources used by the application.\n */\n async dispose() {\n if (this.moduleLoader) {\n this.moduleLoader.dispose()\n }\n }\n\n /**\n * Closes the application and cleans up resources.\n *\n * This should be called when the application is no longer needed to free up resources.\n *\n * @example\n * ```typescript\n * await app.run(process.argv)\n * await app.close()\n * ```\n */\n async close() {\n await this.dispose()\n }\n}\n","import type { ClassTypeWithInstance, NaviosModule } from '@navios/core'\n\nimport { Container } from '@navios/core'\n\nimport type { CommanderApplicationOptions } from './commander.application.mjs'\n\nimport { CommanderApplication } from './commander.application.mjs'\n\n/**\n * Factory class for creating and configuring CLI applications.\n *\n * @example\n * ```typescript\n * import { CommanderFactory } from '@navios/commander'\n * import { AppModule } from './app.module'\n *\n * async function bootstrap() {\n * const app = await CommanderFactory.create(AppModule)\n * await app.init()\n * await app.run(process.argv)\n * await app.close()\n * }\n * ```\n */\nexport class CommanderFactory {\n /**\n * Creates a new CommanderApplication instance and configures it with the provided module.\n *\n * @param appModule - The root CLI module class that contains commands and/or imports other modules\n * @param options - Optional configuration options for the application\n * @returns A promise that resolves to a configured CommanderApplication instance\n *\n * @example\n * ```typescript\n * const app = await CommanderFactory.create(AppModule)\n * await app.init()\n * ```\n */\n static async create(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: CommanderApplicationOptions = {},\n ) {\n const container = new Container()\n const app = await container.get(CommanderApplication)\n await app.setup(appModule, options)\n return app\n }\n}\n","import type { ClassType } from '@navios/core'\nimport type { ZodObject } from 'zod'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/core'\n\nimport { getCommandMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for the `@Command` decorator.\n *\n * @public\n */\nexport interface CommandOptions {\n /**\n * The command path that users will invoke from the CLI.\n * Can be a single word (e.g., 'greet') or multi-word with colons (e.g., 'user:create', 'db:migrate').\n */\n path: string\n /**\n * Optional Zod schema for validating command options.\n * If provided, options will be validated and parsed according to this schema.\n */\n optionsSchema?: ZodObject\n}\n\n/**\n * Decorator that marks a class as a CLI command.\n *\n * The decorated class must implement the `CommandHandler` interface with an `execute` method.\n * The command will be automatically registered when its module is loaded.\n *\n * @param options - Configuration options for the command\n * @returns A class decorator function\n *\n * @example\n * ```typescript\n * import { Command, CommandHandler } from '@navios/commander'\n * import { z } from 'zod'\n *\n * const optionsSchema = z.object({\n * name: z.string(),\n * greeting: z.string().optional().default('Hello')\n * })\n *\n * @Command({\n * path: 'greet',\n * optionsSchema: optionsSchema\n * })\n * export class GreetCommand implements CommandHandler<z.infer<typeof optionsSchema>> {\n * async execute(options) {\n * console.log(`${options.greeting}, ${options.name}!`)\n * }\n * }\n * ```\n */\nexport function Command({ path, optionsSchema }: CommandOptions) {\n return function (target: ClassType, context: ClassDecoratorContext) {\n if (context.kind !== 'class') {\n throw new Error(\n '[Navios Commander] @Command decorator can only be used on classes.',\n )\n }\n const token = InjectionToken.create(target)\n if (context.metadata) {\n getCommandMetadata(target, context, path, optionsSchema)\n }\n return Injectable({\n token,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/core'\n\nimport { getCliModuleMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for the `@CliModule` decorator.\n *\n * @public\n */\nexport interface CliModuleOptions {\n /**\n * Array or Set of command classes to register in this module.\n * Commands must be decorated with `@Command`.\n */\n commands?: ClassType[] | Set<ClassType>\n /**\n * Array or Set of other CLI modules to import.\n * Imported modules' commands will be available in this module.\n */\n imports?: ClassType[] | Set<ClassType>\n}\n\n/**\n * Decorator that marks a class as a CLI module.\n *\n * Modules organize commands and can import other modules to compose larger CLI applications.\n * The module can optionally implement `NaviosModule` interface for lifecycle hooks.\n *\n * @param options - Configuration options for the module\n * @returns A class decorator function\n *\n * @example\n * ```typescript\n * import { CliModule } from '@navios/commander'\n * import { GreetCommand } from './greet.command'\n * import { UserModule } from './user.module'\n *\n * @CliModule({\n * commands: [GreetCommand],\n * imports: [UserModule]\n * })\n * export class AppModule {}\n * ```\n */\nexport function CliModule(\n { commands = [], imports = [] }: CliModuleOptions = {\n commands: [],\n imports: [],\n },\n) {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error(\n '[Navios Commander] @CliModule decorator can only be used on classes.',\n )\n }\n // Register the module in the service locator\n const token = InjectionToken.create(target)\n const moduleMetadata = getCliModuleMetadata(target, context)\n for (const command of commands) {\n moduleMetadata.commands.add(command)\n }\n for (const importedModule of imports) {\n moduleMetadata.imports.add(importedModule)\n }\n\n return Injectable({\n token,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","// Re-export DI types and values that users might need\nexport * from '@navios/core'\n\n// Export commander-specific exports\nexport * from './commander.application.mjs'\nexport * from './commander.factory.mjs'\nexport * from './decorators/index.mjs'\nexport * from './interfaces/index.mjs'\nexport * from './metadata/index.mjs'\nexport * from './services/index.mjs'\nexport * from './tokens/index.mjs'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAaA,sBAAsBC,OAAO,sBAAA;AAmB1C,SAAgBC,uBACdC,SAA4D;AAE5D,KAAIA,QAAQC,UAAU;EACpB,MAAMA,WAAWD,QAAQC,SAASJ;AAGlC,MAAII,SACF,QAAOA;OACF;AACLD,WAAQC,SAASJ,uCAAuB,IAAIK,KAAAA;AAC5C,UAAOF,QAAQC,SAASJ;;;AAG5B,OAAM,IAAIM,MAAM,8BAAA;;AAGlB,SAAgBC,oBACdC,QACAL,SAAoC;AAEpC,KAAIA,QAAQC,UAAU;EACpB,MAAMA,WAAWF,uBAAuBC,QAAAA;AACxC,MAAIC,UAAU;GACZ,MAAMK,mBAAmBC,MAAMC,KAAKP,SAAAA,CAAUQ,MAC3CC,SAASA,KAAKC,gBAAgBN,OA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MAAMC,cAAAA;AAE5C,qCAAkB;GAChBK;GACAG,OAAOb,4BAAgBc;GACzB,CAAA,CAAGR,QAAQC,QAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GCvBf,SAAgBY,UACd,EAAEC,WAAW,EAAE,EAAEC,UAAU,EAAE,KAAuB;CAClDD,UAAU,EAAE;CACZC,SAAS,EAAE;CACZ,EAAA;AAED,SAAQC,QAAmBC,YAAAA;AACzB,MAAIA,QAAQC,SAAS,QACnB,OAAM,IAAIC,MACR,uEAAA;EAIJ,MAAMC,QAAQT,2BAAeU,OAAOL,OAAAA;EACpC,MAAMM,iBAAiBV,qBAAqBI,QAAQC,QAAAA;AACpD,OAAK,MAAMM,WAAWT,SACpBQ,gBAAeR,SAASU,IAAID,QAAAA;AAE9B,OAAK,MAAME,kBAAkBV,QAC3BO,gBAAeP,QAAQS,IAAIC,eAAAA;AAG7B,qCAAkB;GAChBL;GACAM,OAAOhB,4BAAgBiB;GACzB,CAAA,CAAGX,QAAQC,QAAAA"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["EndpointMetadataKey","Symbol","getAllEndpointMetadata","context","metadata","Set","Error","getEndpointMetadata","target","endpointMetadata","Array","from","find","item","classMethod","name","newMetadata","url","successStatusCode","adapterToken","headers","httpMethod","config","guards","customAttributes","Map","add","getAllEndpointMetadata","ControllerMetadataKey","Symbol","getControllerMetadata","target","context","metadata","endpointsMetadata","newMetadata","endpoints","guards","Set","customAttributes","Map","Error","extractControllerMetadata","hasControllerMetadata","ModuleMetadataKey","Symbol","getModuleMetadata","target","context","metadata","newMetadata","controllers","Set","imports","guards","customAttributes","Map","Error","extractModuleMetadata","name","hasModuleMetadata","Injectable","InjectionToken","getControllerMetadata","Controller","guards","registry","target","context","kind","Error","token","create","metadata","controllerMetadata","guard","Array","from","reverse","add","InjectionToken","EndpointAdapterToken","create","InjectionToken","ExecutionContextInjectionToken","ExecutionContext","create","InjectionToken","HttpAdapterToken","create","InjectionToken","MultipartAdapterToken","create","InjectionToken","NaviosOptionsToken","create","InjectionToken","Reply","create","InjectionToken","Request","create","InjectionToken","StreamAdapterToken","create","InjectionToken","XmlStreamAdapterToken","create","getEndpointMetadata","EndpointAdapterToken","Endpoint","endpoint","target","context","kind","Error","config","metadata","endpointMetadata","url","method","adapterToken","classMethod","name","httpMethod","getEndpointMetadata","Header","name","value","target","context","kind","Error","metadata","headers","getEndpointMetadata","HttpCode","code","target","context","kind","Error","metadata","successStatusCode","Injectable","InjectableScope","InjectionToken","getModuleMetadata","Module","controllers","imports","guards","target","context","kind","Error","token","create","moduleMetadata","controller","add","importedModule","guard","Array","from","reverse","scope","Singleton","getEndpointMetadata","MultipartAdapterToken","Multipart","endpoint","target","context","kind","Error","config","metadata","endpointMetadata","url","method","adapterToken","classMethod","name","httpMethod","getEndpointMetadata","StreamAdapterToken","Stream","endpoint","target","context","kind","Error","config","metadata","endpointMetadata","url","method","adapterToken","classMethod","name","httpMethod","getControllerMetadata","getEndpointMetadata","UseGuards","guards","target","context","kind","controllerMetadata","guard","reverse","add","endpointMetadata","Error","client: Client | null","LOG_LEVELS","LOG_LEVELS","isLogLevel","maybeLogLevel","includes","LOG_LEVELS","isLogLevel","filterLogLevels","parseableString","sanitizedString","replaceAll","toLowerCase","orEqual","logLevelIndex","indexOf","substring","Error","slice","includes","split","filter","LOG_LEVEL_VALUES","verbose","debug","log","warn","error","fatal","isLogLevelEnabled","targetLevel","logLevels","Array","isArray","length","includes","highestLogLevelValue","map","level","sort","a","b","targetLevelValue","AsyncLocalStorage","requestCounter","generateRequestId","requestIdStore","getRequestIdStore","requestIdEnabled","setRequestIdEnabled","enabled","runWithRequestId","requestId","fn","run","getRequestId","undefined","getStore","InjectionToken","z","LoggerOutput","create","loggerOptionsSchema","object","context","string","optional","Logger","inspect","Injectable","getRequestId","LoggerOutput","clc","isFunction","isLogLevelEnabled","isPlainObject","isString","isUndefined","yellow","DEFAULT_DEPTH","DEFAULT_LOG_LEVELS","dateTimeFormatter","Intl","DateTimeFormat","undefined","year","hour","minute","second","day","month","token","ConsoleLogger","options","context","originalContext","inspectOptions","getInspectOptions","lastTimestampAt","setup","contextOrOptions","opts","logLevels","colors","json","prefix","log","message","optionalParams","isLevelEnabled","messages","getContextAndMessagesToPrint","printMessages","error","stack","getContextAndStackAndMessagesToPrint","printStackTrace","warn","debug","verbose","fatal","setLogLevels","levels","setContext","resetContext","level","getCurrentRequestId","requestId","getTimestamp","format","Date","now","logLevel","writeStreamType","errorStack","resolvedRequestId","forEach","printAsJson","pidMessage","formatPid","process","pid","contextMessage","formatContext","timestampDiff","updateAndGetTimestampDiff","formattedLogLevel","toUpperCase","padStart","formattedMessage","formatMessage","write","logObject","timestamp","compact","JSON","stringify","stringifyReplacer","output","stringifyMessage","colorize","messageAsStr","Function","prototype","toString","call","isClass","startsWith","name","outputText","Object","keys","length","Array","isArray","color","getColorByLogLevel","stderr","includeTimestamp","result","formatTimestampDiff","formattedDiff","breakLength","Infinity","depth","sorted","showHidden","maxArrayLength","maxStringLength","key","value","Map","Set","Error","args","lastElement","isContext","slice","isStackFormat","isStack","test","magentaBright","red","cyanBright","bold","green","inject","Injectable","Logger","LoggerOutput","token","LoggerInstance","config","context","localInstance","error","message","optionalParams","length","undefined","concat","log","warn","debug","verbose","fatal","NaviosError","inject","Injectable","InjectionToken","z","Logger","ConfigServiceOptionsSchema","record","string","unknown","ConfigServiceToken","create","Symbol","for","token","ConfigService","config","logger","context","name","getConfig","get","key","parts","String","split","value","part","undefined","error","debug","getOrDefault","defaultValue","getOrThrow","errorMessage","message","env","InjectionToken","z","ConfigServiceOptionsSchema","ConfigServiceToken","ConfigProviderOptions","object","load","function","output","provideConfig","options","factory","EnvConfigProvider","bound","HttpException","statusCode","response","error","HttpException","BadRequestException","message","HttpException","ForbiddenException","message","HttpException","InternalServerErrorException","message","error","HttpException","NotFoundException","response","error","HttpException","UnauthorizedException","message","error","HttpException","ConflictException","message","error","Container","getInjectableToken","inject","Injectable","InjectableScope","InstanceResolverService","container","resolve","classType","cachedInstance","get","token","getRegistry","updateScope","Request","cached","instance","scoped","resolveMany","classTypes","length","instances","results","Promise","all","map","success","allCached","every","r","cachedInstances","ControllerResolverService","inject","Injectable","HttpException","Logger","GuardRunnerService","logger","context","name","runGuards","allGuards","executionContext","guardsArray","Array","from","reverse","guardInstances","Promise","all","map","guard","guardInstance","get","canActivate","Error","executeGuards","runGuardsStatic","error","getReply","status","statusCode","send","response","message","makeContext","moduleMetadata","controllerMetadata","endpoint","guards","Set","endpointGuards","controllerGuards","moduleGuards","size","add","Container","inject","Injectable","Logger","extractModuleMetadata","ModuleLoaderService","logger","context","name","container","modulesMetadata","Map","loadedModules","initialized","loadModules","appModule","traverseModules","extendModules","extensions","Error","extension","module","controllers","moduleName","registerControllers","has","existing","get","controller","add","debug","length","metadata","Set","imports","guards","customAttributes","set","parentMetadata","mergeMetadata","loadingPromises","Array","from","map","importedModule","Promise","all","instance","onModuleInit","error","guard","key","value","getAllModules","dispose","clear","getControllerMetadata","getEndpointMetadata","getModuleMetadata","hasControllerMetadata","hasModuleMetadata","AttributeFactory","createAttribute","token","schema","res","value","target","context","kind","Error","isController","isModule","metadata","validatedValue","safeParse","success","toString","error","customAttributes","set","data","get","attribute","getAll","values","Array","from","entries","filter","key","map","length","getLast","i","has","Injectable","NaviosEnvironment","httpTokens","Map","setupHttpEnvironment","tokens","getHttpToken","token","get","hasHttpSetup","size","Factory","inject","NaviosEnvironment","EndpointAdapterToken","token","EndpointAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","HttpAdapterToken","token","HttpAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","MultipartAdapterToken","token","MultipartAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","InjectableScope","NaviosEnvironment","Request","token","scope","RequestFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","InjectableScope","NaviosEnvironment","Reply","token","scope","Request","ReplyFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","StreamAdapterToken","token","StreamAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Factory","inject","NaviosEnvironment","XmlStreamAdapterToken","token","XmlStreamAdapterFactory","environment","create","ctx","service","getHttpToken","Error","Container","inject","Injectable","HttpAdapterToken","Logger","NaviosEnvironment","ModuleLoaderService","NaviosApplication","environment","moduleLoader","httpApplication","logger","context","name","container","appModule","options","adapter","plugins","isInitialized","setup","hasHttpSetup","get","getContainer","usePlugin","definition","push","init","Error","loadModules","setupHttpServer","initPlugins","initModules","ready","debug","modules","getAllModules","onModulesInit","length","server","getServer","globalPrefix","getGlobalPrefix","plugin","register","enableCors","enableMultipart","setGlobalPrefix","prefix","listen","dispose","close","Container","InjectableScope","InjectableType","isNil","LoggerOutput","NaviosApplication","NaviosEnvironment","setRequestIdEnabled","NaviosOptionsToken","NaviosFactory","create","appModule","options","adapter","container","enableRequestId","getServiceLocator","getManager","storeCreatedHolder","toString","Class","Singleton","registerLoggerConfiguration","adapters","Array","isArray","registerEnvironment","app","get","setup","environment","naviosEnvironment","httpTokens","setupHttpEnvironment","logger","loggerInstance","logLevels","$","LOG_LEVELS","A","Logger","B","isFunction","C","EnvConfigProvider","D","_ConfigService","E","ConfigServiceToken","F","runWithRequestId","G","isString","H","isNumber","I","setRequestIdEnabled","J","normalizePath","K","isSymbol","L","addLeadingSlash","M","loggerOptionsSchema","N","generateRequestId","O","_LoggerInstance","P","getRequestId","Q","isLogLevel","R","isConstructor","S","ConfigProviderOptions","T","ConfigServiceOptionsSchema","U","isObject","V","isNil","W","isPlainObject","X","isLogLevelEnabled","Y","stripEndSlash","Z","filterLogLevels","_","NotFoundException","a","_ReplyFactory","b","BadRequestException","c","_HttpAdapterFactory","d","_ModuleLoaderService","et","clc","f","_GuardRunnerService","g","UnauthorizedException","h","ConflictException","i","_StreamAdapterFactory","j","LoggerOutput","k","_ConsoleLogger","l","_EndpointAdapterFactory","m","_InstanceResolverService","n","_NaviosApplication","nt","envInt","o","_RequestFactory","p","ControllerResolverService","q","isUndefined","r","_XmlStreamAdapterFactory","rt","envString","s","_MultipartAdapterFactory","t","NaviosFactory","tt","yellow","u","AttributeFactory","v","InternalServerErrorException","w","provideConfig","x","HttpException","y","ForbiddenException","z","isEmpty","ControllerMetadataKey","EndpointMetadataKey","hasControllerMetadata","getAllEndpointMetadata","hasModuleMetadata","getControllerMetadata","EndpointAdapterToken","HttpCode","extractModuleMetadata","XmlStreamAdapterToken","Reply","NaviosOptionsToken","ExecutionContextInjectionToken","ExecutionContext","Module","getEndpointMetadata","StreamAdapterToken","HttpAdapterToken","Stream","Header","MultipartAdapterToken","Multipart","Endpoint","UseGuards","Request","Controller","extractControllerMetadata","getModuleMetadata","ModuleMetadataKey","ConfigService","ConsoleLogger","EndpointAdapterFactory","GuardRunnerService","HttpAdapterFactory","InstanceResolverService","LoggerInstance","ModuleLoaderService","MultipartAdapterFactory","NaviosApplication","ReplyFactory","RequestFactory","StreamAdapterFactory","XmlStreamAdapterFactory","CommanderExecutionContext","command","commandPath","options","getCommand","getCommandPath","getOptions","CommandMetadataKey","Symbol","getCommandMetadata","target","context","path","optionsSchema","metadata","newMetadata","customAttributes","Map","Error","extractCommandMetadata","hasCommandMetadata","CliModuleMetadataKey","Symbol","getCliModuleMetadata","target","context","metadata","newMetadata","commands","Set","imports","customAttributes","Map","Error","extractCliModuleMetadata","name","hasCliModuleMetadata","Container","inject","Injectable","extractCliModuleMetadata","extractCommandMetadata","CliModuleLoaderService","container","modulesMetadata","Map","loadedModules","commandsMetadata","initialized","loadModules","appModule","traverseModules","module","parentMetadata","metadata","mergeMetadata","moduleName","name","has","set","command","commands","commandMetadata","path","class","imports","Set","loadingPromises","Array","from","map","importedModule","Promise","all","instance","get","onModuleInit","customAttributes","key","value","getAllModules","getAllCommands","values","getAllCommandsWithMetadata","getCommandByPath","dispose","clear","Injectable","CliParserService","parse","argv","optionsSchema","args","slice","length","Error","booleanFields","extractBooleanFields","Set","arrayFields","extractArrayFields","commandParts","i","startsWith","push","command","join","options","positionals","arg","key","equalIndex","indexOf","optionName","optionValue","camelCaseKey","camelCase","isArray","has","parseValue","isBoolean","nextArg","flags","flag","str","replace","_","letter","toUpperCase","value","undefined","test","parseInt","parseFloat","endsWith","JSON","schema","typeName","def","type","shape","fieldSchema","Object","entries","isSchemaBoolean","add","isSchemaArray","currentSchema","_def","innerType","innerTypeName","formatCommandList","commands","lines","path","InjectionToken","CommandExecutionContextInjectionToken","CommandExecutionContext","create","Container","inject","Injectable","CommanderExecutionContext","CliModuleLoaderService","CliParserService","CommandExecutionContext","CommanderApplication","moduleLoader","cliParser","container","appModule","options","isInitialized","setup","getContainer","init","Error","loadModules","executeCommand","commandPath","commandWithMetadata","getCommandByPath","class","commandClass","metadata","validatedOptions","optionsSchema","parse","executionContext","requestId","Date","now","Math","random","toString","substring","scopeContainer","beginRequest","addInstance","commandInstance","get","execute","endRequest","getAllCommands","commandsMap","getAllCommandsWithMetadata","commandsWithMetadata","cmd","push","path","run","argv","process","preliminaryParse","command","parsed","help","h","commands","console","log","formatCommandList","error","message","includes","dispose","close","Container","CommanderApplication","CommanderFactory","create","appModule","options","container","app","get","setup","Injectable","InjectableScope","InjectionToken","getCommandMetadata","Command","path","optionsSchema","target","context","kind","Error","token","create","metadata","scope","Singleton","Injectable","InjectableScope","InjectionToken","getCliModuleMetadata","CliModule","commands","imports","target","context","kind","Error","token","create","moduleMetadata","command","add","importedModule","scope","Singleton"],"sources":["../../src/metadata/handler.metadata.mts","../../src/metadata/controller.metadata.mts","../../src/metadata/module.metadata.mts","../../src/decorators/controller.decorator.mts","../../src/tokens/endpoint-adapter.token.mts","../../src/tokens/execution-context.token.mts","../../src/tokens/http-adapter.token.mts","../../src/tokens/multipart-adapter.token.mts","../../src/tokens/navios-options.token.mts","../../src/tokens/reply.token.mts","../../src/tokens/request.token.mts","../../src/tokens/stream-adapter.token.mts","../../src/tokens/xml-stream-adapter.token.mts","../../src/decorators/endpoint.decorator.mts","../../src/decorators/header.decorator.mts","../../src/decorators/http-code.decorator.mts","../../src/decorators/module.decorator.mts","../../src/decorators/multipart.decorator.mts","../../src/decorators/stream.decorator.mts","../../src/decorators/use-guards.decorator.mts","../../src/errors/navios-error.mts","../../src/errors/handle-error.mts","../../src/request/bind-url-params.mts","../../src/request/make-config.mts","../../src/handlers/create-handler.mts","../../src/handlers/endpoint.mts","../../src/handlers/multipart.mts","../../src/handlers/stream.mts","../../src/builder.mts","../../src/config/utils/helpers.mts","../../src/logger/utils/cli-colors.util.mts","../../src/logger/log-levels.mts","../../src/logger/utils/is-log-level.util.mts","../../src/logger/utils/filter-log-levelts.util.mts","../../src/logger/utils/is-log-level-enabled.mts","../../src/logger/utils/shared.utils.mts","../../src/stores/request-id.store.mts","../../src/logger/logger.tokens.mts","../../src/logger/console-logger.service.mts","../../src/logger/logger.service.mts","../../src/config/config.service.mts","../../src/config/config.provider.mts","../../src/exceptions/http.exception.mts","../../src/exceptions/bad-request.exception.mts","../../src/exceptions/forbidden.exception.mts","../../src/exceptions/internal-server-error.exception.mts","../../src/exceptions/not-found.exception.mts","../../src/exceptions/unauthorized.exception.mts","../../src/exceptions/conflict.exception.mts","../../src/services/instance-resolver.service.mts","../../src/services/guard-runner.service.mts","../../src/services/module-loader.service.mts","../../src/attribute.factory.mts","../../src/navios.environment.mts","../../src/factories/endpoint-adapter.factory.mts","../../src/factories/http-adapter.factory.mts","../../src/factories/multipart-adapter.factory.mts","../../src/factories/request.factory.mts","../../src/factories/reply.factory.mts","../../src/factories/stream-adapter.factory.mts","../../src/factories/xml-stream-adapter.factory.mts","../../src/navios.application.mts","../../src/navios.factory.mts","../../core/lib/index.mjs","../src/interfaces/commander-execution-context.interface.mts","../src/metadata/command.metadata.mts","../src/metadata/cli-module.metadata.mts","../src/services/module-loader.service.mts","../src/services/cli-parser.service.mts","../src/tokens/execution-context.token.mts","../src/commander.application.mts","../src/commander.factory.mts","../src/decorators/command.decorator.mts","../src/decorators/cli-module.decorator.mts","../src/index.mts"],"sourcesContent":["import type { HttpMethod } from '@navios/builder'\nimport type { ClassTypeWithInstance, InjectionToken } from '@navios/di'\n\nimport type {\n AbstractHttpHandlerAdapterInterface,\n CanActivate,\n HttpHeader,\n} from '../interfaces/index.mjs'\n\nexport const EndpointMetadataKey = Symbol('EndpointMetadataKey')\n\nexport interface HandlerMetadata<Config = null> {\n classMethod: string\n url: string\n successStatusCode: number\n adapterToken:\n | InjectionToken<AbstractHttpHandlerAdapterInterface, undefined>\n | ClassTypeWithInstance<AbstractHttpHandlerAdapterInterface>\n | null\n headers: Partial<Record<HttpHeader, number | string | string[] | undefined>>\n httpMethod: HttpMethod\n config: Config\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<HandlerMetadata<any>> {\n if (context.metadata) {\n const metadata = context.metadata[EndpointMetadataKey] as\n | Set<HandlerMetadata>\n | undefined\n if (metadata) {\n return metadata\n } else {\n context.metadata[EndpointMetadataKey] = new Set<HandlerMetadata<any>>()\n return context.metadata[EndpointMetadataKey] as Set<HandlerMetadata<any>>\n }\n }\n throw new Error('[Navios] Wrong environment.')\n}\n\nexport function getEndpointMetadata<Config = any>(\n target: Function,\n context: ClassMethodDecoratorContext,\n): HandlerMetadata<Config> {\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: HandlerMetadata<Config> = {\n classMethod: target.name,\n url: '',\n successStatusCode: 200,\n adapterToken: null,\n headers: {},\n httpMethod: 'GET',\n // @ts-expect-error We are using a generic type here\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 {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport type { CanActivate } from '../interfaces/index.mjs'\nimport type { HandlerMetadata } from './handler.metadata.mjs'\n\nimport { getAllEndpointMetadata } from './handler.metadata.mjs'\n\nexport const ControllerMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ControllerMetadata {\n endpoints: Set<HandlerMetadata>\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 {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport type { CanActivate } from '../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 for ${target.name}. 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 '@navios/di'\n\nimport { Injectable, InjectionToken, Registry } from '@navios/di'\n\nimport { getControllerMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a Navios controller.\n */\nexport interface ControllerOptions {\n /**\n * Guards to apply to all endpoints in this controller.\n * Guards are executed in reverse order (last guard first).\n */\n guards?: ClassType[] | Set<ClassType>\n /**\n * Registry to use for the controller.\n * Registry is used to store the controller and its endpoints.\n */\n registry?: Registry\n}\n\n/**\n * Decorator that marks a class as a Navios controller.\n *\n * Controllers handle HTTP requests and define endpoints.\n * They are request-scoped by default, meaning a new instance is created for each request.\n *\n * @param options - Controller configuration options\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * @Controller({ guards: [AuthGuard] })\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * // Handle request\n * }\n * }\n * ```\n */\nexport function Controller({ guards, registry }: 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 registry,\n })(target, context)\n }\n}\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const EndpointAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'EndpointAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractExecutionContext } from '../interfaces/index.mjs'\n\nexport const ExecutionContextInjectionToken = 'ExecutionContextInjectionToken'\n\nexport const ExecutionContext = InjectionToken.create<AbstractExecutionContext>(\n ExecutionContextInjectionToken,\n)\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpAdapterInterface } from '../interfaces/index.mjs'\n\nexport const HttpAdapterToken =\n InjectionToken.create<AbstractHttpAdapterInterface<any, any, any, any>>(\n 'HttpAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const MultipartAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'MultipartAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { NaviosApplicationOptions } from '../navios.application.mjs'\n\nexport const NaviosOptionsToken =\n InjectionToken.create<NaviosApplicationOptions>('NaviosOptionsToken')\n","import { InjectionToken } from '@navios/di'\n\nexport const Reply = InjectionToken.create<any>('ReplyToken')\n","import { InjectionToken } from '@navios/di'\n\nexport const Request = InjectionToken.create<any>('RequestToken')\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const StreamAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'StreamAdapterToken',\n )\n","import { InjectionToken } from '@navios/di'\n\nimport type { AbstractHttpHandlerAdapterInterface } from '../interfaces/index.mjs'\n\nexport const XmlStreamAdapterToken =\n InjectionToken.create<AbstractHttpHandlerAdapterInterface>(\n 'XmlStreamAdapterToken',\n )\n","import type {\n BaseEndpointConfig,\n EndpointFunctionArgs,\n HttpMethod,\n Util_FlatObject,\n} from '@navios/builder'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { ZodDiscriminatedUnion } from 'zod/v4'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\nimport { EndpointAdapterToken } from '../tokens/index.mjs'\n\n/**\n * Extracts the typed parameters for an endpoint handler function.\n *\n * This utility type extracts URL parameters, query parameters, and request body\n * from an endpoint declaration and flattens them into a single object.\n *\n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n *\n * @example\n * ```typescript\n * const getUserEndpoint = api.declareEndpoint({\n * method: 'get',\n * url: '/users/$userId',\n * querySchema: z.object({ include: z.string().optional() }),\n * responseSchema: z.object({ id: z.string(), name: z.string() }),\n * })\n *\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * // request.urlParams.userId is typed as string\n * // request.query.include is typed as string | undefined\n * }\n * ```\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 ZodType\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, QuerySchema, undefined, true>>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, undefined, undefined, true>>\n\n/**\n * Extracts the typed return value for an endpoint handler function.\n *\n * This utility type extracts the response schema from an endpoint declaration\n * and returns the appropriate Promise type.\n *\n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n *\n * @example\n * ```typescript\n * const getUserEndpoint = api.declareEndpoint({\n * method: 'get',\n * url: '/users/$userId',\n * responseSchema: z.object({ id: z.string(), name: z.string() }),\n * })\n *\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>): EndpointResult<typeof getUserEndpoint> {\n * return { id: '1', name: 'John' } // Type-checked against responseSchema\n * }\n * ```\n */\nexport type EndpointResult<\n EndpointDeclaration extends {\n config: BaseEndpointConfig<any, any, any, any, any>\n },\n> =\n EndpointDeclaration['config']['responseSchema'] extends ZodDiscriminatedUnion<\n infer Options\n >\n ? Promise<z.input<Options[number]>>\n : Promise<z.input<EndpointDeclaration['config']['responseSchema']>>\n\n/**\n * Decorator that marks a method as an HTTP endpoint.\n *\n * The endpoint must be defined using @navios/builder's `declareEndpoint` method.\n * This ensures type safety and consistency between client and server.\n *\n * @param endpoint - The endpoint declaration from @navios/builder\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * import { builder } from '@navios/builder'\n *\n * const api = builder()\n * const getUserEndpoint = api.declareEndpoint({\n * method: 'get',\n * url: '/users/$userId',\n * responseSchema: z.object({ id: z.string(), name: z.string() }),\n * })\n *\n * @Controller()\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * const { userId } = request.urlParams\n * return { id: userId, name: 'John' }\n * }\n * }\n * ```\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 Params = QuerySchema extends ZodType\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>,\n>(endpoint: {\n config: BaseEndpointConfig<\n Method,\n Url,\n QuerySchema,\n ResponseSchema,\n RequestSchema\n >\n}): (\n target: (\n params: Params,\n ) => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>,\n context: ClassMethodDecoratorContext,\n) => void\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 target: () => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>,\n context: ClassMethodDecoratorContext,\n) => void\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 type Params = QuerySchema extends ZodType\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>\n\n type Handler =\n | ((\n params: Params,\n ) => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>)\n | (() => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>)\n\n return (target: Handler, context: ClassMethodDecoratorContext) => {\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<BaseEndpointConfig>(\n target,\n context,\n )\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.adapterToken = EndpointAdapterToken\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 '../interfaces/index.mjs'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that sets a custom HTTP response header for an endpoint.\n * \n * @param name - The header name (e.g., 'Content-Type', 'Cache-Control')\n * @param value - The header value (string, number, or array of strings)\n * @returns A method decorator\n * \n * @example\n * ```typescript\n * @Controller()\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * @Header('Cache-Control', 'max-age=3600')\n * async getUser() {\n * return { id: '1', name: 'John' }\n * }\n * }\n * ```\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\n metadata.headers[name] = value\n\n return target\n }\n}\n","import { getEndpointMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that sets a custom HTTP status code for successful responses.\n * \n * By default, endpoints return 200 OK. Use this decorator to return a different status code.\n * \n * @param code - The HTTP status code to return (e.g., 201, 204, 202)\n * @returns A method decorator\n * \n * @example\n * ```typescript\n * @Controller()\n * export class UserController {\n * @Endpoint(createUserEndpoint)\n * @HttpCode(201)\n * async createUser() {\n * return { id: '1', name: 'John' }\n * }\n * }\n * ```\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 '@navios/di'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/di'\n\nimport { getModuleMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a Navios module.\n */\nexport interface ModuleOptions {\n /**\n * Controllers to register in this module.\n * Controllers handle HTTP requests and define endpoints.\n */\n controllers?: ClassType[] | Set<ClassType>\n /**\n * Other modules to import into this module.\n * Imported modules' controllers and services become available.\n */\n imports?: ClassType[] | Set<ClassType>\n /**\n * Guards to apply to all controllers in this module.\n * Guards are executed in reverse order (last guard first).\n */\n guards?: ClassType[] | Set<ClassType>\n}\n\n/**\n * Decorator that marks a class as a Navios module.\n * \n * Modules are the basic building blocks of a Navios application.\n * They organize controllers, services, and other modules into logical units.\n * \n * @param options - Module configuration options\n * @returns A class decorator\n * \n * @example\n * ```typescript\n * @Module({\n * controllers: [UserController, AuthController],\n * imports: [DatabaseModule],\n * guards: [AuthGuard],\n * })\n * export class AppModule {}\n * ```\n */\nexport function Module(\n { controllers = [], imports = [], guards = [] }: ModuleOptions = {\n controllers: [],\n imports: [],\n guards: [],\n },\n) {\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 for (const controller of controllers) {\n moduleMetadata.controllers.add(controller)\n }\n for (const importedModule of imports) {\n moduleMetadata.imports.add(importedModule)\n }\n for (const guard of Array.from(guards).reverse()) {\n moduleMetadata.guards.add(guard)\n }\n\n return Injectable({\n token,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","import type {\n BaseEndpointConfig,\n EndpointFunctionArgs,\n HttpMethod,\n Util_FlatObject,\n} from '@navios/builder'\nimport type { z, ZodObject, ZodType } from 'zod/v4'\n\nimport { ZodDiscriminatedUnion } from 'zod/v4'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\nimport { MultipartAdapterToken } from '../tokens/index.mjs'\n\n/**\n * Extracts the typed parameters for a multipart endpoint handler function.\n *\n * Similar to `EndpointParams`, but specifically for multipart/form-data endpoints.\n *\n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n */\nexport type MultipartParams<\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 ZodObject\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, QuerySchema, undefined, true>>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, undefined, undefined, true>>\n\n/**\n * Extracts the typed return value for a multipart endpoint handler function.\n *\n * @typeParam EndpointDeclaration - The endpoint declaration from @navios/builder\n */\nexport type MultipartResult<\n EndpointDeclaration extends {\n config: BaseEndpointConfig<any, any, any, any, any>\n },\n> =\n EndpointDeclaration['config']['responseSchema'] extends ZodDiscriminatedUnion<\n infer Options\n >\n ? Promise<z.input<Options[number]>>\n : Promise<z.input<EndpointDeclaration['config']['responseSchema']>>\n\n/**\n * Decorator that marks a method as a multipart/form-data endpoint.\n *\n * Use this decorator for endpoints that handle file uploads or form data.\n * The endpoint must be defined using @navios/builder's `declareMultipart` method.\n *\n * @param endpoint - The multipart endpoint declaration from @navios/builder\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * const uploadFileEndpoint = api.declareMultipart({\n * method: 'post',\n * url: '/upload',\n * requestSchema: z.object({ file: z.instanceof(File) }),\n * responseSchema: z.object({ url: z.string() }),\n * })\n *\n * @Controller()\n * export class FileController {\n * @Multipart(uploadFileEndpoint)\n * async uploadFile(request: MultipartParams<typeof uploadFileEndpoint>) {\n * const { file } = request.data\n * // Handle file upload\n * return { url: 'https://example.com/file.jpg' }\n * }\n * }\n * ```\n */\nexport function Multipart<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n ResponseSchema extends ZodType = ZodType,\n RequestSchema = ZodType,\n Params = QuerySchema extends ZodObject\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>,\n>(endpoint: {\n config: BaseEndpointConfig<\n Method,\n Url,\n QuerySchema,\n ResponseSchema,\n RequestSchema\n >\n}): (\n target: (\n params: Params,\n ) => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>,\n context: ClassMethodDecoratorContext,\n) => void\nexport function Multipart<\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 target: () => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>,\n context: ClassMethodDecoratorContext,\n) => void\nexport function Multipart<\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 type Params = QuerySchema extends ZodObject\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>\n\n type Handler =\n | ((\n params: Params,\n ) => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>)\n | (() => Promise<z.input<ResponseSchema>> | z.input<ResponseSchema>)\n\n return (target: Handler, context: ClassMethodDecoratorContext) => {\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<BaseEndpointConfig>(\n target,\n context,\n )\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.adapterToken = MultipartAdapterToken\n endpointMetadata.classMethod = target.name\n endpointMetadata.httpMethod = config.method\n endpointMetadata.url = config.url\n }\n return target\n }\n}\n","import type {\n BaseStreamConfig,\n EndpointFunctionArgs,\n HttpMethod,\n Util_FlatObject,\n} from '@navios/builder'\nimport type { ZodObject, ZodType } from 'zod/v4'\n\nimport { getEndpointMetadata } from '../metadata/index.mjs'\nimport { StreamAdapterToken } from '../tokens/index.mjs'\n\n/**\n * Extracts the typed parameters for a stream endpoint handler function.\n *\n * Similar to `EndpointParams`, but specifically for streaming endpoints.\n *\n * @typeParam EndpointDeclaration - The stream endpoint declaration from @navios/builder\n */\nexport type StreamParams<\n EndpointDeclaration extends {\n config: BaseStreamConfig<any, any, any, any>\n },\n Url extends string = EndpointDeclaration['config']['url'],\n QuerySchema = EndpointDeclaration['config']['querySchema'],\n> = QuerySchema extends ZodObject\n ? EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n QuerySchema,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, QuerySchema, undefined, true>>\n : EndpointDeclaration['config']['requestSchema'] extends ZodType\n ? Util_FlatObject<\n EndpointFunctionArgs<\n Url,\n undefined,\n EndpointDeclaration['config']['requestSchema'],\n true\n >\n >\n : Util_FlatObject<EndpointFunctionArgs<Url, undefined, undefined, true>>\n\n/**\n * Decorator that marks a method as a streaming endpoint.\n *\n * Use this decorator for endpoints that stream data (e.g., file downloads, SSE).\n * The endpoint must be defined using @navios/builder's `declareStream` method.\n *\n * @param endpoint - The stream endpoint declaration from @navios/builder\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * const downloadFileEndpoint = api.declareStream({\n * method: 'get',\n * url: '/files/$fileId',\n * })\n *\n * @Controller()\n * export class FileController {\n * @Stream(downloadFileEndpoint)\n * async downloadFile(request: StreamParams<typeof downloadFileEndpoint>, reply: any) {\n * const { fileId } = request.urlParams\n * // Stream file data to reply\n * }\n * }\n * ```\n */\nexport function Stream<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n RequestSchema = ZodType,\n Params = QuerySchema extends ZodObject\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>,\n>(endpoint: {\n config: BaseStreamConfig<Method, Url, QuerySchema, RequestSchema>\n}): (\n target: (params: Params, reply: any) => any,\n context: ClassMethodDecoratorContext,\n) => void\n// Bun doesn't support reply parameter\nexport function Stream<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n RequestSchema = ZodType,\n Params = QuerySchema extends ZodObject\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>,\n>(endpoint: {\n config: BaseStreamConfig<Method, Url, QuerySchema, RequestSchema>\n}): (\n target: (params: Params) => any,\n context: ClassMethodDecoratorContext,\n) => void\nexport function Stream<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n RequestSchema = ZodType,\n>(endpoint: {\n config: BaseStreamConfig<Method, Url, QuerySchema, RequestSchema>\n}): (target: () => any, context: ClassMethodDecoratorContext) => void\nexport function Stream<\n Method extends HttpMethod = HttpMethod,\n Url extends string = string,\n QuerySchema = undefined,\n RequestSchema = ZodType,\n>(endpoint: {\n config: BaseStreamConfig<Method, Url, QuerySchema, RequestSchema>\n}) {\n type Params = QuerySchema extends ZodObject\n ? RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, QuerySchema, RequestSchema, true>\n : EndpointFunctionArgs<Url, QuerySchema, undefined, true>\n : RequestSchema extends ZodType\n ? EndpointFunctionArgs<Url, undefined, RequestSchema, true>\n : EndpointFunctionArgs<Url, undefined, undefined, true>\n\n type Handler =\n | ((params: Params, reply: any) => any)\n | ((params: Params) => any)\n | (() => any)\n\n return (target: Handler, context: ClassMethodDecoratorContext) => {\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<BaseStreamConfig>(\n target,\n context,\n )\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.adapterToken = StreamAdapterToken\n endpointMetadata.classMethod = target.name\n endpointMetadata.httpMethod = config.method\n endpointMetadata.url = config.url\n }\n return target\n }\n}\n","import type {\n ClassType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport type { CanActivate } from '../interfaces/index.mjs'\n\nimport {\n getControllerMetadata,\n getEndpointMetadata,\n} from '../metadata/index.mjs'\n\n/**\n * Decorator that applies guards to a controller or endpoint.\n * \n * Guards are used for authentication, authorization, and request validation.\n * They implement the `CanActivate` interface and are executed before the endpoint handler.\n * Guards can be applied at the module, controller, or endpoint level.\n * \n * @param guards - Guard classes or injection tokens to apply\n * @returns A class or method decorator\n * \n * @example\n * ```typescript\n * // Apply to a controller\n * @Controller()\n * @UseGuards(AuthGuard, RoleGuard)\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * async getUser() { }\n * }\n * \n * // Apply to a specific endpoint\n * @Controller()\n * export class UserController {\n * @Endpoint(getUserEndpoint)\n * @UseGuards(AuthGuard)\n * async getUser() { }\n * }\n * ```\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","/**\n * Custom error class for Navios Builder errors.\n *\n * This error is thrown when:\n * - No HTTP client has been provided via `provideClient`\n * - Other builder-specific errors occur\n *\n * @example\n * ```ts\n * try {\n * API.getClient()\n * } catch (error) {\n * if (error instanceof NaviosError) {\n * console.error('Navios error:', error.message)\n * }\n * }\n * ```\n */\nexport class NaviosError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'NaviosError'\n }\n}\n\n/**\n * @deprecated Use NaviosError instead. Will be removed in next major version.\n */\nexport const NaviosException = NaviosError\n","import type { ZodType } from 'zod/v4'\n\nimport { ZodError } from 'zod/v4'\n\nimport type { AbstractResponse, BuilderConfig } from '../types/index.mjs'\n\n/**\n * Handles errors that occur during HTTP requests.\n *\n * This function implements the error handling strategy based on the builder configuration:\n * - Calls `onError` callback if provided (always called first)\n * - If `useDiscriminatorResponse` is `true` and the error has a response, attempts to parse\n * the error response using the same `responseSchema` as success responses\n * - Calls `onZodError` callback if validation fails\n * - Throws the error if it cannot be handled as a discriminated response\n *\n * @param config - Builder configuration containing error handling callbacks\n * @param error - The error that occurred (can be any type)\n * @param responseSchema - Optional Zod schema to validate error responses when\n * `useDiscriminatorResponse` is enabled\n * @returns The parsed error response data if `useDiscriminatorResponse` is enabled\n * and parsing succeeds, otherwise throws the error\n * @throws The original error or a ZodError if validation fails\n *\n * @example\n * ```ts\n * // With useDiscriminatorResponse: true\n * const result = handleError(\n * { useDiscriminatorResponse: true },\n * { response: { data: { status: 'error', message: 'Not found' } } },\n * z.discriminatedUnion('status', [\n * z.object({ status: z.literal('success'), data: z.any() }),\n * z.object({ status: z.literal('error'), message: z.string() })\n * ])\n * )\n * // Returns: { status: 'error', message: 'Not found' }\n * ```\n */\nexport function handleError(\n config: BuilderConfig,\n error: unknown,\n responseSchema?: ZodType,\n) {\n if (config.onError) {\n config.onError(error)\n }\n if (!config.useDiscriminatorResponse) {\n if (config.onZodError && error instanceof ZodError) {\n config.onZodError(error, undefined, undefined)\n }\n throw error\n }\n if (\n responseSchema &&\n typeof error === 'object' &&\n error &&\n 'response' in error &&\n error.response\n ) {\n const response = error.response as AbstractResponse<any>\n try {\n return responseSchema.parse(response.data)\n } catch (e) {\n if (config.onZodError) {\n config.onZodError(e as ZodError, response, error)\n }\n throw e\n }\n }\n throw error\n}\n\n/**\n * @deprecated Use handleError instead. Will be removed in next major version.\n */\nexport const handleException = handleError\n","import type { BaseEndpointConfig, NaviosZodRequest } from '../types/index.mjs'\n\n/**\n * Binds URL parameters to a URL template string.\n *\n * Replaces placeholders in the format `$paramName` with actual values from `urlParams`.\n * All parameter values are URL-encoded to ensure safe inclusion in URLs.\n *\n * @param urlPart - URL template with parameter placeholders (e.g., '/users/$userId/posts/$postId')\n * @param params - Request parameters object containing `urlParams` with parameter values\n * @returns The URL with parameters replaced and URL-encoded\n * @throws {Error} If required URL parameters are missing\n *\n * @example\n * ```ts\n * const url = bindUrlParams('/users/$userId/posts/$postId', {\n * urlParams: { userId: '123', postId: '456' }\n * })\n * // Returns: '/users/123/posts/456'\n *\n * // With special characters (automatically encoded)\n * const url2 = bindUrlParams('/search/$query', {\n * urlParams: { query: 'hello world' }\n * })\n * // Returns: '/search/hello%20world'\n * ```\n */\nexport function bindUrlParams<Url extends string>(\n urlPart: Url,\n params: NaviosZodRequest<BaseEndpointConfig<any, Url, any, any, any>>,\n) {\n const placement = /\\$([a-zA-Z0-9]+)/g\n const matches = Array.from(urlPart.matchAll(placement))\n\n if (matches.length === 0) {\n return urlPart\n }\n\n // Extract all required param names\n const requiredParams = matches.map(([, group]) => group)\n\n // Validate that urlParams exists and contains all required params\n if (!params.urlParams) {\n throw new Error(\n `Missing urlParams. Required parameters: ${requiredParams.join(', ')}`,\n )\n }\n\n // Validate that all required params are present\n const missingParams = requiredParams.filter(\n (param) => params.urlParams![param as string] === undefined,\n )\n if (missingParams.length > 0) {\n throw new Error(\n `Missing required URL parameters: ${missingParams.join(', ')}`,\n )\n }\n\n // Single-pass replacement using callback to avoid issues with values containing $\n const result = urlPart.replace(placement, (_, paramName: string) => {\n const value = params.urlParams![paramName]\n return encodeURIComponent(String(value))\n })\n\n return result as Url\n}\n","import type { ZodType } from 'zod/v4'\n\nimport type {\n AbstractRequestConfig,\n BaseStreamConfig,\n HttpMethod,\n NaviosZodRequest,\n} from '../types/index.mjs'\n\nfunction parseWithSchema(schema: ZodType | undefined, value: unknown): unknown {\n return schema ? schema.parse(value) : value\n}\n\n/**\n * Creates a request configuration object for the HTTP client.\n *\n * This function:\n * - Validates and parses query parameters using `querySchema` (if provided)\n * - Validates and parses request body data using `requestSchema` (if provided)\n * - Converts request data to FormData if `isMultipart` is true\n * - Merges all request properties (headers, signal, etc.) into the final config\n *\n * @param request - The request parameters object\n * @param options - Endpoint configuration containing schemas\n * @param method - HTTP method to use\n * @param finalUrlPart - The final URL with parameters bound\n * @param isMultipart - Whether to convert the request data to FormData\n * @returns A request configuration object compatible with the Client interface\n *\n * @internal\n */\nexport function makeConfig<Config extends BaseStreamConfig>(\n request: NaviosZodRequest<Config>,\n options: Config,\n method: HttpMethod,\n finalUrlPart: string,\n isMultipart = false,\n) {\n return {\n ...request,\n params: parseWithSchema(options.querySchema as ZodType | undefined, request.params ?? {}) as Record<string, unknown>,\n method,\n url: finalUrlPart,\n data: isMultipart\n ? makeFormData(request, options)\n : parseWithSchema(options.requestSchema as ZodType | undefined, request.data),\n } satisfies AbstractRequestConfig\n}\n\n/**\n * Serializes a value for inclusion in FormData.\n *\n * Handles various types:\n * - File instances are returned as-is\n * - null/undefined become empty strings\n * - Dates are converted to ISO strings\n * - Objects with toISOString or toJSON methods are serialized appropriately\n * - Other objects are JSON stringified\n * - Primitives are converted to strings\n *\n * @param value - The value to serialize\n * @returns A string representation or File instance\n * @internal\n */\nfunction serializeFormDataValue(value: unknown): string | File {\n if (value instanceof File) {\n return value\n }\n if (value == null) {\n return ''\n }\n if (typeof value === 'string') {\n return value\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value)\n }\n if (value instanceof Date) {\n return value.toISOString()\n }\n if (typeof value === 'object') {\n if ('toISOString' in value && typeof value.toISOString === 'function') {\n return value.toISOString()\n }\n if ('toJSON' in value && typeof value.toJSON === 'function') {\n return String(value.toJSON())\n }\n return JSON.stringify(value)\n }\n return String(value)\n}\n\n/**\n * Converts request data to FormData for multipart/form-data requests.\n *\n * The function:\n * - Validates the request data against `requestSchema` (if provided)\n * - Creates a FormData instance\n * - Appends all fields, handling File instances, arrays, and other types appropriately\n * - Files are appended with their name property\n * - Arrays of files are appended individually\n * - Other values are serialized using `serializeFormDataValue`\n *\n * @param request - The request parameters object\n * @param options - Endpoint configuration containing request schema\n * @returns A FormData instance ready for multipart requests\n *\n * @example\n * ```ts\n * const formData = makeFormData(\n * { data: { file: new File(['content'], 'file.txt'), name: 'My File' } },\n * { requestSchema: z.object({ file: z.instanceof(File), name: z.string() }) }\n * )\n * ```\n *\n * @internal\n */\nexport function makeFormData<Config extends BaseStreamConfig>(\n request: NaviosZodRequest<Config>,\n options: Config,\n) {\n const formData = new FormData()\n const validatedRequest = parseWithSchema(\n options.requestSchema as ZodType | undefined,\n request.data,\n ) as Record<string, unknown>\n for (const key in validatedRequest) {\n const value = validatedRequest[key]\n if (value instanceof File) {\n formData.append(key, value, value.name)\n } else if (Array.isArray(value)) {\n for (const item of value) {\n if (item instanceof File) {\n formData.append(key, item, item.name)\n } else {\n formData.append(key, serializeFormDataValue(item))\n }\n }\n } else {\n const serialized = serializeFormDataValue(value)\n if (serialized instanceof File) {\n formData.append(key, serialized, serialized.name)\n } else {\n formData.append(key, serialized)\n }\n }\n }\n return formData\n}\n","import type { ZodType } from 'zod/v4'\n\nimport type {\n BaseStreamConfig,\n BuilderContext,\n NaviosZodRequest,\n} from '../types/index.mjs'\n\nimport { handleError } from '../errors/handle-error.mjs'\nimport { bindUrlParams } from '../request/bind-url-params.mjs'\nimport { makeConfig } from '../request/make-config.mjs'\n\nexport interface CreateHandlerOptions<Config extends BaseStreamConfig> {\n options: Config\n context: BuilderContext\n isMultipart?: boolean\n responseSchema?: ZodType\n transformRequest?: (request: NaviosZodRequest<Config>) => NaviosZodRequest<Config>\n transformResponse?: (data: unknown) => unknown\n}\n\nexport function createHandler<Config extends BaseStreamConfig, TResponse>({\n options,\n context: { getClient, config },\n isMultipart = false,\n responseSchema,\n transformRequest,\n transformResponse,\n}: CreateHandlerOptions<Config>) {\n const { method, url } = options\n\n const handler = async (\n request: NaviosZodRequest<Config> = {} as NaviosZodRequest<Config>,\n ): Promise<TResponse> => {\n const client = getClient()\n const finalUrlPart = bindUrlParams<Config['url']>(url, request)\n const finalRequest = transformRequest ? transformRequest(request) : request\n\n try {\n const result = await client.request(\n makeConfig(finalRequest, options, method, finalUrlPart, isMultipart),\n )\n\n const data = transformResponse ? transformResponse(result.data) : result.data\n\n return (responseSchema ? responseSchema.parse(data) : data) as TResponse\n } catch (error) {\n // handleError may return a parsed response (when useDiscriminatorResponse is true)\n // or throw an error\n return handleError(config, error, responseSchema) as TResponse\n }\n }\n\n handler.config = options\n\n return handler\n}\n","import type { z } from 'zod/v4'\n\nimport type { BaseEndpointConfig, BuilderContext } from '../types/index.mjs'\n\nimport { createHandler } from './create-handler.mjs'\n\n/**\n * Creates an endpoint handler function with request/response validation.\n *\n * The returned function will:\n * - Validate request data against `requestSchema` (if provided)\n * - Validate query parameters against `querySchema` (if provided)\n * - Make the HTTP request using the configured client\n * - Validate and parse the response against `responseSchema`\n * - Handle errors according to the builder configuration\n *\n * @param options - Endpoint configuration\n * @param options.method - HTTP method (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)\n * @param options.url - URL pattern with optional parameters (e.g., '/users/$userId')\n * @param options.responseSchema - Zod schema for validating the response\n * @param options.requestSchema - Optional Zod schema for validating request body (POST, PUT, PATCH only)\n * @param options.querySchema - Optional Zod schema for validating query parameters\n * @param context - Builder context containing client getter and configuration\n * @returns A function that makes the HTTP request and returns validated response data\n *\n * @example\n * ```ts\n * const getUser = createEndpoint({\n * method: 'GET',\n * url: '/users/$userId',\n * responseSchema: z.object({ id: z.string(), name: z.string() })\n * }, context)\n *\n * const user = await getUser({ urlParams: { userId: '123' } })\n * ```\n */\nexport function createEndpoint<Config extends BaseEndpointConfig>(\n options: Config,\n context: BuilderContext,\n) {\n return createHandler<Config, z.output<Config['responseSchema']>>({\n options,\n context,\n responseSchema: options.responseSchema,\n })\n}\n","import type { z } from 'zod/v4'\n\nimport type { BaseEndpointConfig, BuilderContext } from '../types/index.mjs'\n\nimport { createHandler } from './create-handler.mjs'\n\n/**\n * Creates a multipart/form-data handler function for file uploads.\n *\n * The returned function will:\n * - Validate request data against `requestSchema` (if provided)\n * - Convert the request data to FormData automatically\n * - Handle File instances and other data types appropriately\n * - Validate query parameters against `querySchema` (if provided)\n * - Make the HTTP request with FormData\n * - Validate and parse the response against `responseSchema`\n *\n * @param options - Multipart endpoint configuration\n * @param options.method - HTTP method (POST, PUT, or PATCH)\n * @param options.url - URL pattern with optional parameters (e.g., '/upload/$userId')\n * @param options.responseSchema - Zod schema for validating the response\n * @param options.requestSchema - Optional Zod schema for validating request data (should include File types)\n * @param options.querySchema - Optional Zod schema for validating query parameters\n * @param context - Builder context containing client getter and configuration\n * @returns A function that makes the HTTP request with FormData and returns validated response data\n *\n * @example\n * ```ts\n * const uploadFile = createMultipart({\n * method: 'POST',\n * url: '/upload',\n * requestSchema: z.object({\n * file: z.instanceof(File),\n * description: z.string()\n * }),\n * responseSchema: z.object({ id: z.string(), url: z.string() })\n * }, context)\n *\n * const result = await uploadFile({\n * data: {\n * file: new File(['content'], 'file.txt'),\n * description: 'My file'\n * }\n * })\n * ```\n */\nexport function createMultipart<Config extends BaseEndpointConfig>(\n options: Config,\n context: BuilderContext,\n) {\n return createHandler<Config, z.output<Config['responseSchema']>>({\n options,\n context,\n isMultipart: true,\n responseSchema: options.responseSchema,\n })\n}\n","import type { BaseStreamConfig, BuilderContext, NaviosZodRequest } from '../types/index.mjs'\n\nimport { createHandler } from './create-handler.mjs'\n\n/**\n * Creates a stream handler function for downloading files as Blob.\n *\n * The returned function will:\n * - Validate request data against `requestSchema` (if provided)\n * - Validate query parameters against `querySchema` (if provided)\n * - Make the HTTP request with `responseType: 'blob'`\n * - Return the response as a Blob\n *\n * @param options - Stream endpoint configuration\n * @param options.method - HTTP method\n * @param options.url - URL pattern with optional parameters (e.g., '/files/$fileId')\n * @param options.requestSchema - Optional Zod schema for validating request body (POST, PUT, PATCH only)\n * @param options.querySchema - Optional Zod schema for validating query parameters\n * @param context - Builder context containing client getter and configuration\n * @returns A function that makes the HTTP request and returns a Blob\n *\n * @example\n * ```ts\n * const downloadFile = createStream({\n * method: 'GET',\n * url: '/files/$fileId',\n * querySchema: z.object({ format: z.enum(['pdf', 'docx']) })\n * }, context)\n *\n * const blob = await downloadFile({\n * urlParams: { fileId: '123' },\n * params: { format: 'pdf' }\n * })\n * ```\n */\nexport function createStream<Config extends BaseStreamConfig>(\n options: Config,\n context: BuilderContext,\n) {\n return createHandler<Config, Blob>({\n options,\n context,\n transformRequest: (request: NaviosZodRequest<Config>) => ({\n responseType: 'blob',\n ...request,\n }),\n transformResponse: (data) => data as Blob,\n })\n}\n","import type {\n BaseEndpointConfig,\n BaseStreamConfig,\n BuilderConfig,\n BuilderInstance,\n Client,\n} from './types/index.mjs'\n\nimport { NaviosError } from './errors/index.mjs'\nimport { createEndpoint, createMultipart, createStream } from './handlers/index.mjs'\n\n/**\n * Creates a new API builder instance with the specified configuration.\n *\n * The builder allows you to declaratively define API endpoints with type-safe\n * request and response schemas using Zod. It supports discriminated unions for\n * handling different response types, error handling callbacks, and various\n * HTTP methods.\n *\n * @param config - Configuration options for the builder\n * @param config.useDiscriminatorResponse - If `true`, error responses will be\n * parsed using the same responseSchema as success responses. This is useful\n * when your API returns discriminated unions that include both success and\n * error cases. Default is `false`.\n * @param config.onError - Optional callback function that will be called when\n * any error occurs during a request. This is called before the error is thrown\n * or processed.\n * @param config.onZodError - Optional callback function that will be called when\n * a Zod validation error occurs. This is called after `onError` if provided.\n * Useful for logging validation errors or showing user-friendly messages.\n *\n * @returns A BuilderInstance with methods to declare endpoints and manage the HTTP client\n *\n * @example\n * ```ts\n * const API = builder({\n * useDiscriminatorResponse: true,\n * onError: (error) => console.error('Request failed:', error),\n * onZodError: (error, response) => {\n * console.error('Validation failed:', error.errors)\n * }\n * })\n * ```\n */\nexport function builder(config: BuilderConfig = {}): BuilderInstance {\n let client: Client | null = null\n\n /**\n * Gets the current HTTP client instance.\n *\n * @returns The configured HTTP client\n * @throws {NaviosError} If no client has been provided via `provideClient`\n */\n function getClient() {\n if (!client) {\n throw new NaviosError('[Navios-API]: Client was not provided')\n }\n return client\n }\n\n /**\n * Declares a new API endpoint with request/response validation.\n *\n * @param options - Endpoint configuration\n * @returns A function that makes the HTTP request and returns validated response data\n */\n function declareEndpoint(options: BaseEndpointConfig) {\n return createEndpoint(options, {\n getClient,\n config,\n })\n }\n\n /**\n * Declares a new stream endpoint for downloading files as Blob.\n *\n * @param options - Stream endpoint configuration\n * @returns A function that makes the HTTP request and returns a Blob\n */\n function declareStream(options: BaseStreamConfig) {\n return createStream(options, {\n getClient,\n config,\n })\n }\n\n /**\n * Declares a new multipart/form-data endpoint for file uploads.\n *\n * The request data will be automatically converted to FormData.\n *\n * @param options - Multipart endpoint configuration\n * @returns A function that makes the HTTP request with FormData and returns validated response data\n */\n function declareMultipart(options: BaseEndpointConfig) {\n return createMultipart(options, {\n getClient,\n config,\n })\n }\n\n /**\n * Sets or replaces the HTTP client instance used by all endpoints.\n *\n * The client must implement the `Client` interface with a `request` method.\n * Compatible with axios, @navios/http, and any client that follows the same interface.\n *\n * @param newClient - The HTTP client instance to use for all requests\n *\n * @example\n * ```ts\n * import { create } from '@navios/http'\n * const client = create({ baseURL: 'https://api.example.com' })\n * API.provideClient(client)\n * ```\n */\n function provideClient(newClient: Client) {\n client = newClient\n }\n\n return {\n declareEndpoint,\n declareStream,\n declareMultipart,\n provideClient,\n getClient,\n }\n}\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","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","/**\n * Available log levels in order of severity (lowest to highest).\n */\nexport const LOG_LEVELS = [\n 'verbose',\n 'debug',\n 'log',\n 'warn',\n 'error',\n 'fatal',\n] as const satisfies string[]\n\n/**\n * Log level type.\n * \n * Represents the severity level of a log message.\n * Levels are: 'verbose', 'debug', 'log', 'warn', 'error', 'fatal'\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 { AsyncLocalStorage } from 'node:async_hooks'\n\nlet requestCounter = 0\n\n/**\n * Generates a simple incremental request ID.\n * Much faster than crypto.randomUUID() and sufficient for request tracking.\n *\n * @returns A unique request ID string (e.g., \"req-1\", \"req-2\", ...)\n */\nexport function generateRequestId(): string {\n return `req-${++requestCounter}`\n}\n\n/**\n * AsyncLocalStorage store for the current request ID.\n *\n * This allows logging and other services to access the current request ID\n * without explicitly passing it through the call stack.\n *\n * @example\n * ```typescript\n * import { requestIdStore, runWithRequestId, getRequestId } from '@navios/core'\n *\n * // Run code with a request ID in context\n * runWithRequestId('req-123', () => {\n * // Inside this callback, getRequestId() returns 'req-123'\n * logger.log('Processing request') // Will include request ID if logger is configured\n * })\n *\n * // Get current request ID (returns undefined if not in a request context)\n * const currentId = getRequestId()\n * ```\n */\nlet requestIdStore: AsyncLocalStorage<string> | null = null\n\nfunction getRequestIdStore(): AsyncLocalStorage<string> {\n if (!requestIdStore) {\n requestIdStore = new AsyncLocalStorage<string>()\n }\n return requestIdStore!\n}\n/**\n * Whether request ID propagation is enabled.\n * When disabled, runWithRequestId is a pass-through for better performance.\n */\nlet requestIdEnabled = false\n\n/**\n * Enables or disables request ID propagation.\n * Called by NaviosFactory based on the enableRequestId option.\n *\n * @param enabled - Whether to enable request ID propagation\n */\nexport function setRequestIdEnabled(enabled: boolean): void {\n requestIdEnabled = enabled\n}\n\n/**\n * Runs a function with a request ID in the async local storage context.\n * If request ID propagation is disabled, the function is called directly\n * without AsyncLocalStorage overhead.\n *\n * @param requestId - The request ID to set for this context\n * @param fn - The function to run within this context\n * @returns The return value of the function\n */\nexport function runWithRequestId<R>(requestId: string, fn: () => R): R {\n if (!requestIdEnabled) {\n return fn()\n }\n return getRequestIdStore().run(requestId, fn)\n}\n\n/**\n * Gets the current request ID from the async local storage context.\n *\n * @returns The current request ID, or undefined if not in a request context\n */\nexport function getRequestId(): string | undefined {\n if (!requestIdEnabled) {\n return undefined\n }\n return getRequestIdStore().getStore()\n}\n","import { InjectionToken } from '@navios/di'\n\nimport z from 'zod/v4'\n\nimport type { LoggerService } from './logger-service.interface.mjs'\nimport type { LoggerInstance } from './logger.service.mjs'\n\n/**\n * Injection token for the logger output service.\n * \n * This token is used to provide a custom logger implementation.\n * By default, it's bound to ConsoleLogger.\n */\nexport const LoggerOutput = InjectionToken.create<LoggerService>('LoggerOutput')\n\n/**\n * Schema for logger options.\n */\nexport const loggerOptionsSchema = z\n .object({\n context: z.string().optional(),\n })\n .optional()\n\n/**\n * Options for creating a logger instance.\n */\nexport type LoggerOptions = z.infer<typeof loggerOptionsSchema>\n\n/**\n * Injection token for the Logger service.\n * \n * Use this token to inject a contextualized logger instance.\n * \n * @example\n * ```typescript\n * const logger = inject(Logger, { context: 'MyService' })\n * logger.log('Hello world') // Logs with context: [MyService]\n * ```\n */\nexport const Logger = InjectionToken.create<\n LoggerInstance,\n typeof loggerOptionsSchema\n>('Logger', loggerOptionsSchema)\n","import type { InspectOptions } from 'util'\n\nimport { inspect } from 'util'\n\nimport { Injectable } from '@navios/di'\n\nimport type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-service.interface.mjs'\n\nimport { getRequestId } from '../stores/request-id.store.mjs'\nimport { LoggerOutput } from './logger.tokens.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 add a request ID to the log message.\n */\n requestId?: boolean\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({\n token: LoggerOutput,\n})\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 = this.getInspectOptions()\n /**\n * The last timestamp at which the log message was printed.\n */\n protected lastTimestampAt?: number\n\n setup(): void\n setup(context: string): void\n setup(options: ConsoleLoggerOptions): void\n setup(context: string, options: ConsoleLoggerOptions): void\n setup(\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', undefined, '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 /**\n * Gets the current request ID from the AsyncLocalStorage store.\n * Only returns a value if the requestId option is enabled.\n */\n protected getCurrentRequestId(): string | undefined {\n if (!this.options.requestId) {\n return undefined\n }\n return getRequestId()\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 requestId?: string,\n writeStreamType?: 'stdout' | 'stderr',\n errorStack?: unknown,\n ) {\n const resolvedRequestId = requestId ?? this.getCurrentRequestId()\n messages.forEach((message) => {\n if (this.options.json) {\n this.printAsJson(message, {\n context,\n logLevel,\n writeStreamType,\n errorStack,\n requestId: resolvedRequestId,\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 resolvedRequestId,\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 requestId?: string\n },\n ) {\n type JsonLogObject = {\n level: LogLevel\n pid: number\n timestamp: number\n message: unknown\n context?: string\n stack?: unknown\n requestId?: string\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 if (this.options.requestId && options.requestId) {\n logObject.requestId = options.requestId\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 requestId?: 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.getRequestId(requestId)}${this.getTimestamp()} ${formattedLogLevel} ${contextMessage}${output}${timestampDiff}\\n`\n }\n\n protected getRequestId(requestId?: string) {\n if (this.options.requestId && requestId) {\n return `(${this.colorize(requestId, 'log')}) `\n }\n return ''\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 = this.lastTimestampAt && this.options?.timestamp\n const result = includeTimestamp\n ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt!)\n : ''\n this.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 { inject, Injectable } from '@navios/di'\n\nimport type { LoggerService } from './logger-service.interface.mjs'\nimport type { LoggerOptions } from './logger.tokens.mjs'\n\nimport { Logger, LoggerOutput } from './logger.tokens.mjs'\n\n/**\n * Logger service instance that can be injected into services and controllers.\n *\n * Provides contextualized logging with automatic context injection.\n * The context is set when the logger is injected using the `inject` function.\n *\n * @example\n * ```typescript\n * @Injectable()\n * export class UserService {\n * private logger = inject(Logger, { context: UserService.name })\n *\n * async findUser(id: string) {\n * this.logger.log(`Finding user ${id}`)\n * // Logs with context: [UserService]\n * }\n * }\n * ```\n */\n@Injectable({\n token: Logger,\n})\nexport class LoggerInstance implements LoggerService {\n protected localInstance = inject(LoggerOutput)\n\n protected context?: string\n\n constructor(config: LoggerOptions = {}) {\n this.context = config.context\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","import { NaviosError } from '@navios/builder'\nimport { inject, Injectable, InjectionToken } from '@navios/di'\n\nimport { z } from 'zod/v4'\n\nimport type { ConfigServiceInterface as IConfigService } from './config-service.interface.mjs'\nimport type { Path, PathValue } from './types.mjs'\n\nimport { Logger } from '../logger/index.mjs'\n\n/**\n * Schema for validating configuration service options.\n */\nexport const ConfigServiceOptionsSchema = z.record(z.string(), z.unknown())\n/**\n * Type for configuration service options.\n */\nexport type ConfigServiceOptions = z.infer<typeof ConfigServiceOptionsSchema>\n\n/**\n * Injection token for ConfigService.\n */\nexport const ConfigServiceToken = InjectionToken.create<\n IConfigService,\n typeof ConfigServiceOptionsSchema\n>(Symbol.for('ConfigService'), ConfigServiceOptionsSchema)\n\n/**\n * Service for managing application configuration with type-safe access.\n *\n * Provides methods to access configuration values using dot-notation paths\n * with full TypeScript type inference.\n *\n * @typeParam Config - The configuration object type\n *\n * @example\n * ```typescript\n * interface AppConfig {\n * database: {\n * host: string\n * port: number\n * }\n * api: {\n * timeout: number\n * }\n * }\n *\n * @Injectable()\n * export class DatabaseService {\n * private config = inject(MyConfigService)\n *\n * connect() {\n * const host = this.config.getOrThrow('database.host')\n * const port = this.config.getOrDefault('database.port', 5432)\n * // host is typed as string, port is typed as number\n * }\n * }\n * ```\n */\n@Injectable({\n token: ConfigServiceToken,\n})\nexport class ConfigService<\n Config extends ConfigServiceOptions = Record<string, unknown>,\n> implements IConfigService<Config> {\n private readonly logger = inject(Logger, {\n context: ConfigService.name,\n })\n\n /**\n * Creates a new ConfigService instance.\n *\n * @param config - The configuration object\n */\n constructor(private config: Config = {} as Config) {}\n\n /**\n * Gets the entire configuration object.\n *\n * @returns The complete configuration object\n */\n getConfig(): Config {\n return this.config\n }\n\n /**\n * Gets a configuration value by key path.\n *\n * Returns `null` if the key is not found or if any part of the path is invalid.\n *\n * @param key - Dot-separated path to the configuration value (e.g., 'database.host')\n * @returns The configuration value or `null` if not found\n *\n * @example\n * ```typescript\n * const host = config.get('database.host') // string | null\n * const port = config.get('database.port') // number | null\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 /**\n * Gets a configuration value by key path, or returns a default value if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param defaultValue - Default value to return if the key is not found\n * @returns The configuration value or the default value\n *\n * @example\n * ```typescript\n * const port = config.getOrDefault('database.port', 5432) // number\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 /**\n * Gets a configuration value by key path, or throws an error if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param errorMessage - Optional custom error message\n * @returns The configuration value\n * @throws Error if the key is not found\n *\n * @example\n * ```typescript\n * const host = config.getOrThrow('database.host') // string (throws if not found)\n * const apiKey = config.getOrThrow('api.key', 'API key is required') // string\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 NaviosError(message)\n }\n\n return value\n }\n}\n","import { env } from 'node:process'\n\nimport { FactoryInjectionToken, InjectionToken } from '@navios/di'\n\nimport { z } from 'zod/v4'\n\nimport type { ConfigServiceOptions } from './config.service.mjs'\n\nimport {\n ConfigService,\n ConfigServiceOptionsSchema,\n ConfigServiceToken,\n} from './config.service.mjs'\n\n/**\n * Schema for configuration provider options.\n */\nexport const ConfigProviderOptions = z.object({\n load: z.function({ output: ConfigServiceOptionsSchema }),\n})\n\n/**\n * Creates a factory injection token for ConfigService that loads configuration asynchronously.\n *\n * Use this when you need to load configuration from a file, database, or other async source.\n *\n * @param options - Configuration provider options\n * @param options.load - Async function that loads and returns the configuration object\n * @returns A factory injection token for ConfigService\n *\n * @example\n * ```typescript\n * const MyConfigService = provideConfig({\n * load: async () => {\n * const config = await loadConfigFromFile('config.json')\n * return config\n * },\n * })\n *\n * // Use in module setup\n * container.bind(ConfigServiceToken).toFactory(configProvider)\n * ```\n */\nexport function provideConfig<ConfigMap extends ConfigServiceOptions>(\n options: z.input<typeof ConfigProviderOptions>,\n): FactoryInjectionToken<\n ConfigService<ConfigMap>,\n typeof ConfigServiceOptionsSchema\n> {\n return InjectionToken.factory(ConfigServiceToken, async () => options.load())\n}\n\n/**\n * Pre-configured ConfigService provider that uses environment variables.\n *\n * Provides a ConfigService instance bound to `process.env`.\n *\n * @example\n * ```typescript\n * // Use environment variables as configuration\n * container.bind(ConfigServiceToken).toValue(EnvConfigProvider)\n * ```\n */\nexport const EnvConfigProvider = InjectionToken.bound<\n ConfigService<Record<string, string>>,\n typeof ConfigServiceOptionsSchema\n>(ConfigServiceToken, {\n ...env,\n})\n","/**\n * Base exception class for all HTTP exceptions in Navios.\n * \n * All HTTP exception classes extend this base class. When thrown from an endpoint handler,\n * Navios will automatically convert it to an appropriate HTTP response with the specified\n * status code and response body.\n * \n * @example\n * ```typescript\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * const user = await this.userService.findById(request.urlParams.userId)\n * if (!user) {\n * throw new HttpException(404, 'User not found')\n * }\n * return user\n * }\n * ```\n */\nexport class HttpException {\n /**\n * Creates a new HttpException instance.\n * \n * @param statusCode - HTTP status code (e.g., 400, 404, 500)\n * @param response - Response body (string or object)\n * @param error - Optional underlying error for logging/debugging\n */\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\n/**\n * Exception that represents a 400 Bad Request HTTP error.\n * \n * Use this exception when the client's request is malformed or invalid.\n * \n * @example\n * ```typescript\n * @Endpoint(createUserEndpoint)\n * async createUser(request: EndpointParams<typeof createUserEndpoint>) {\n * if (!request.data.email) {\n * throw new BadRequestException('Email is required')\n * }\n * // ...\n * }\n * ```\n */\nexport class BadRequestException extends HttpException {\n /**\n * Creates a new BadRequestException.\n * \n * @param message - Error message or response object\n */\n constructor(message: string | object) {\n super(400, message)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 403 Forbidden HTTP error.\n * \n * Use this exception when the client is authenticated but does not have\n * permission to access the requested resource.\n * \n * @example\n * ```typescript\n * @Endpoint(deleteUserEndpoint)\n * @UseGuards(AuthGuard, RoleGuard)\n * async deleteUser(request: EndpointParams<typeof deleteUserEndpoint>) {\n * if (!this.userService.hasPermission(request.user, 'delete')) {\n * throw new ForbiddenException('Insufficient permissions')\n * }\n * // ...\n * }\n * ```\n */\nexport class ForbiddenException extends HttpException {\n /**\n * Creates a new ForbiddenException.\n * \n * @param message - Error message\n */\n constructor(message: string) {\n super(403, message)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 500 Internal Server Error HTTP error.\n * \n * Use this exception when an unexpected error occurs on the server.\n * Generally, you should let unhandled errors bubble up rather than catching\n * and rethrowing as InternalServerErrorException, as Navios will handle them appropriately.\n * \n * @example\n * ```typescript\n * @Endpoint(processPaymentEndpoint)\n * async processPayment(request: EndpointParams<typeof processPaymentEndpoint>) {\n * try {\n * return await this.paymentService.process(request.data)\n * } catch (error) {\n * this.logger.error('Payment processing failed', error)\n * throw new InternalServerErrorException('Payment processing failed', error)\n * }\n * }\n * ```\n */\nexport class InternalServerErrorException extends HttpException {\n /**\n * Creates a new InternalServerErrorException.\n * \n * @param message - Error message or response object\n * @param error - Optional underlying error for logging\n */\n constructor(message: string | object, error?: Error) {\n super(500, message, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 404 Not Found HTTP error.\n * \n * Use this exception when the requested resource does not exist.\n * \n * @example\n * ```typescript\n * @Endpoint(getUserEndpoint)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * const user = await this.userService.findById(request.urlParams.userId)\n * if (!user) {\n * throw new NotFoundException('User not found')\n * }\n * return user\n * }\n * ```\n */\nexport class NotFoundException extends HttpException {\n /**\n * Creates a new NotFoundException.\n * \n * @param response - Error message or response object\n * @param error - Optional underlying error for logging\n */\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\n/**\n * Exception that represents a 401 Unauthorized HTTP error.\n * \n * Use this exception when the client is not authenticated or authentication failed.\n * \n * @example\n * ```typescript\n * @Endpoint(getUserEndpoint)\n * @UseGuards(AuthGuard)\n * async getUser(request: EndpointParams<typeof getUserEndpoint>) {\n * if (!request.headers.authorization) {\n * throw new UnauthorizedException('Authentication required')\n * }\n * // ...\n * }\n * ```\n */\nexport class UnauthorizedException extends HttpException {\n /**\n * Creates a new UnauthorizedException.\n * \n * @param message - Error message or response object\n * @param error - Optional underlying error for logging\n */\n constructor(message: string | object, error?: Error) {\n super(401, message, error)\n }\n}\n","import { HttpException } from './http.exception.mjs'\n\n/**\n * Exception that represents a 409 Conflict HTTP error.\n * \n * Use this exception when the request conflicts with the current state of the resource\n * (e.g., trying to create a resource that already exists).\n * \n * @example\n * ```typescript\n * @Endpoint(createUserEndpoint)\n * async createUser(request: EndpointParams<typeof createUserEndpoint>) {\n * const existing = await this.userService.findByEmail(request.data.email)\n * if (existing) {\n * throw new ConflictException('User with this email already exists')\n * }\n * // ...\n * }\n * ```\n */\nexport class ConflictException extends HttpException {\n /**\n * Creates a new ConflictException.\n * \n * @param message - Error message or response object\n * @param error - Optional underlying error for logging\n */\n constructor(message: string | object, error?: Error) {\n super(409, message, error)\n }\n}\n","import type { ClassType, ScopedContainer } from '@navios/di'\n\nimport {\n Container,\n getInjectableToken,\n inject,\n Injectable,\n InjectableScope,\n} from '@navios/di'\n\n/**\n * Result of instance resolution attempt.\n * Contains either a cached singleton instance or a resolver function\n * that can be used to get a fresh instance per request.\n */\nexport interface InstanceResolution<T = any> {\n /**\n * Whether the instance was successfully cached as a singleton.\n * If true, `instance` contains the cached instance.\n * If false, the class has request-scoped dependencies and\n * must be resolved per-request using `resolve()`.\n */\n cached: boolean\n\n /**\n * The cached instance (only available if `cached` is true).\n */\n instance: T | null\n\n /**\n * Resolves the instance from a scoped container.\n * Use this when `cached` is false to get a fresh instance per request.\n */\n resolve: (scoped: ScopedContainer) => Promise<T>\n}\n\n/**\n * Result of resolving multiple instances.\n * Contains either all cached singleton instances or a resolver function.\n */\nexport interface MultiInstanceResolution<T = any> {\n /**\n * Whether ALL instances were successfully cached as singletons.\n * If true, `instances` contains all cached instances.\n * If false, at least one class has request-scoped dependencies.\n */\n cached: boolean\n\n /**\n * The cached instances (only available if `cached` is true).\n * Order matches the input array order.\n */\n instances: T[] | null\n\n /**\n * The original class types for dynamic resolution.\n */\n classTypes: ClassType[]\n\n /**\n * Resolves all instances from a scoped container.\n * Use this when `cached` is false to get fresh instances per request.\n */\n resolve: (scoped: ScopedContainer) => Promise<T[]>\n}\n\n/**\n * Service responsible for resolving class instances with automatic scope detection.\n *\n * This service attempts to resolve classes as singletons from the root container.\n * If resolution fails (because the class has request-scoped dependencies),\n * it automatically updates the class's scope to Request and provides a\n * resolver function for per-request instantiation.\n *\n * This enables optimal performance:\n * - Classes without request-scoped deps stay as singletons (faster)\n * - Classes with request-scoped deps are automatically promoted to request scope\n *\n * @example\n * ```ts\n * const resolution = await instanceResolver.resolve(UserController)\n *\n * if (resolution.cached) {\n * // Use cached singleton\n * return resolution.instance.handleRequest(req)\n * } else {\n * // Resolve per request\n * const controller = await resolution.resolve(scopedContainer)\n * return controller.handleRequest(req)\n * }\n * ```\n */\n@Injectable()\nexport class InstanceResolverService {\n private container = inject(Container)\n\n /**\n * Attempts to resolve a class instance, automatically detecting if it needs\n * request scope based on its dependencies.\n *\n * @param classType - The class to resolve\n * @returns A resolution result containing either a cached instance or resolver function\n */\n async resolve<T>(classType: ClassType): Promise<InstanceResolution<T>> {\n let cachedInstance: T | null = null\n\n try {\n cachedInstance = await this.container.get(classType)\n } catch {\n // Class has request-scoped dependencies, update its scope to Request\n // so it will be resolved per-request from the scoped container\n const token = getInjectableToken(classType)\n this.container\n .getRegistry()\n .updateScope(token, InjectableScope.Request)\n }\n\n return {\n cached: cachedInstance !== null,\n instance: cachedInstance,\n resolve: (scoped: ScopedContainer) =>\n scoped.get(classType) as Promise<T>,\n }\n }\n\n /**\n * Attempts to resolve multiple class instances, automatically detecting if any need\n * request scope based on their dependencies.\n *\n * Returns `cached: true` only if ALL classes can be resolved as singletons.\n * If any class has request-scoped dependencies, returns `cached: false`.\n *\n * @param classTypes - The classes to resolve\n * @returns A resolution result containing either all cached instances or resolver function\n */\n async resolveMany<T>(classTypes: ClassType[]): Promise<MultiInstanceResolution<T>> {\n if (classTypes.length === 0) {\n return {\n cached: true,\n instances: [],\n classTypes: [],\n resolve: async () => [],\n }\n }\n\n // Resolve all classes in parallel\n const results = await Promise.all(\n classTypes.map(async (classType) => {\n try {\n const instance = await this.container.get(classType)\n return { success: true, instance: instance as T }\n } catch {\n // Class has request-scoped dependencies, update its scope to Request\n const token = getInjectableToken(classType)\n this.container\n .getRegistry()\n .updateScope(token, InjectableScope.Request)\n return { success: false, instance: null }\n }\n }),\n )\n\n const allCached = results.every((r) => r.success)\n const cachedInstances = allCached\n ? results.map((r) => r.instance as T)\n : null\n\n return {\n cached: allCached,\n instances: cachedInstances,\n classTypes,\n resolve: (scoped: ScopedContainer) =>\n Promise.all(classTypes.map((classType) => scoped.get(classType) as Promise<T>)),\n }\n }\n}\n\n/**\n * @deprecated Use InstanceResolverService instead\n */\nexport const ControllerResolverService = InstanceResolverService\n\n/**\n * @deprecated Use InstanceResolution instead\n */\nexport type ControllerResolution<T = any> = InstanceResolution<T>\n","import type { ClassTypeWithInstance, ScopedContainer } from '@navios/di'\n\nimport { inject, Injectable, InjectionToken } from '@navios/di'\n\nimport type {\n AbstractExecutionContext,\n CanActivate,\n} from '../interfaces/index.mjs'\nimport type {\n ControllerMetadata,\n HandlerMetadata,\n ModuleMetadata,\n} from '../metadata/index.mjs'\n\nimport { HttpException } from '../exceptions/index.mjs'\nimport { Logger } from '../logger/index.mjs'\n\n@Injectable()\nexport class GuardRunnerService {\n private readonly logger = inject(Logger, {\n context: GuardRunnerService.name,\n })\n\n /**\n * Runs guards that need to be resolved from a scoped container.\n * Use this when guards have request-scoped dependencies.\n */\n async runGuards(\n allGuards: Set<\n | ClassTypeWithInstance<CanActivate>\n | InjectionToken<CanActivate, undefined>\n >,\n executionContext: AbstractExecutionContext,\n context: ScopedContainer,\n ) {\n // Reverse order: module guards run first, then controller, then endpoint\n const guardsArray = Array.from(allGuards).reverse()\n\n // Resolve all guards in parallel\n const guardInstances = await Promise.all(\n guardsArray.map(async (guard) => {\n const guardInstance = await context.get(\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 return guardInstance\n }),\n )\n\n return this.executeGuards(guardInstances, executionContext)\n }\n\n /**\n * Runs pre-resolved guard instances.\n * Use this when all guards are singletons and have been pre-resolved at startup.\n */\n async runGuardsStatic(\n guardInstances: CanActivate[],\n executionContext: AbstractExecutionContext,\n ) {\n return this.executeGuards(guardInstances, executionContext)\n }\n\n /**\n * Shared guard execution logic.\n * Iterates through guard instances and calls canActivate on each.\n */\n private async executeGuards(\n guardInstances: CanActivate[],\n executionContext: AbstractExecutionContext,\n ): Promise<boolean> {\n let canActivate = true\n for (const guardInstance of guardInstances) {\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 this.logger.error('Error running guard', error)\n executionContext.getReply().status(500).send({\n message: 'Internal server error',\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 moduleMetadata: ModuleMetadata,\n controllerMetadata: ControllerMetadata,\n endpoint: HandlerMetadata,\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 = endpoint.guards\n const controllerGuards = controllerMetadata.guards\n const moduleGuards = moduleMetadata.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 { ClassType, ClassTypeWithInstance } from '@navios/di'\n\nimport { Container, inject, Injectable } from '@navios/di'\n\nimport type { NaviosModule } from '../interfaces/index.mjs'\nimport type { ModuleMetadata } from '../metadata/index.mjs'\n\nimport { Logger } from '../logger/index.mjs'\nimport { extractModuleMetadata } from '../metadata/index.mjs'\n\n/**\n * Extension definition for dynamically adding to the module tree.\n * Used by plugins to inject controllers or entire modules.\n */\nexport interface ModuleExtension {\n /**\n * Module class to add. If provided, the module and all its\n * controllers/imports will be processed.\n */\n module?: ClassTypeWithInstance<NaviosModule>\n\n /**\n * Controllers to add directly without a wrapper module.\n * Will be registered under a synthetic module named after the plugin.\n */\n controllers?: ClassType[]\n\n /**\n * Name for the synthetic module when using controllers directly.\n * Required if `controllers` is provided without `module`.\n */\n moduleName?: string\n}\n\n@Injectable()\nexport class ModuleLoaderService {\n private logger = inject(Logger, {\n context: ModuleLoaderService.name,\n })\n protected container = inject(Container)\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 /**\n * Extends the module tree with additional modules or controllers.\n *\n * This method is designed to be called by plugins during registration,\n * which happens after initial module loading but before route registration.\n *\n * @param extensions - Array of module extensions to add\n * @throws Error if not initialized (loadModules must be called first)\n *\n * @example\n * ```typescript\n * // In plugin registration\n * const moduleLoader = await context.container.get(ModuleLoaderService)\n * await moduleLoader.extendModules([{\n * controllers: [OpenApiJsonController, OpenApiYamlController],\n * moduleName: 'OpenApiBunModule',\n * }])\n * ```\n */\n async extendModules(extensions: ModuleExtension[]): Promise<void> {\n if (!this.initialized) {\n throw new Error(\n 'ModuleLoaderService must be initialized before extending. Call loadModules() first.',\n )\n }\n\n for (const extension of extensions) {\n if (extension.module) {\n // Process a full module with its imports and controllers\n await this.traverseModules(extension.module)\n } else if (extension.controllers && extension.moduleName) {\n // Create synthetic module metadata for loose controllers\n await this.registerControllers(\n extension.controllers,\n extension.moduleName,\n )\n } else if (extension.controllers) {\n throw new Error(\n 'moduleName is required when providing controllers without a module',\n )\n }\n }\n }\n\n /**\n * Registers controllers under a synthetic module.\n * Used when plugins want to add controllers without a full module class.\n */\n private async registerControllers(\n controllers: ClassType[],\n moduleName: string,\n ): Promise<void> {\n if (this.modulesMetadata.has(moduleName)) {\n // Merge controllers into existing module\n const existing = this.modulesMetadata.get(moduleName)!\n for (const controller of controllers) {\n existing.controllers.add(controller)\n }\n this.logger.debug(\n `Extended module ${moduleName} with ${controllers.length} controllers`,\n )\n } else {\n // Create new synthetic module metadata\n const metadata: ModuleMetadata = {\n controllers: new Set(controllers),\n imports: new Set(),\n guards: new Set(),\n customAttributes: new Map(),\n }\n this.modulesMetadata.set(moduleName, metadata)\n\n this.logger.debug(\n `Created module ${moduleName} with ${controllers.length} controllers`,\n )\n }\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 try {\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 this.container.get(module)\n if (instance.onModuleInit) {\n await instance.onModuleInit()\n }\n this.logger.debug(`Module ${moduleName} loaded`)\n this.loadedModules.set(moduleName, instance)\n } catch (error) {\n this.logger.error(`Error loading module ${moduleName}`, error)\n throw error\n }\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 dispose() {\n this.modulesMetadata.clear()\n this.loadedModules.clear()\n this.initialized = false\n }\n}\n","import type { ClassType } from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport type {\n ControllerMetadata,\n HandlerMetadata,\n ModuleMetadata,\n} from './metadata/index.mjs'\n\nimport {\n getControllerMetadata,\n getEndpointMetadata,\n getModuleMetadata,\n hasControllerMetadata,\n hasModuleMetadata,\n} from './metadata/index.mjs'\n\n/**\n * Type for a class attribute decorator without a value.\n * \n * Attributes are custom metadata decorators that can be applied to modules,\n * controllers, and endpoints.\n */\nexport type ClassAttribute = (() => <T>(\n target: T,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n) => T) & {\n token: symbol\n}\n\n/**\n * Type for a class attribute decorator with a validated value.\n * \n * @typeParam T - The Zod schema type for validation\n */\nexport type ClassSchemaAttribute<T extends ZodType> = ((\n value: z.input<T>,\n) => <T>(\n target: T,\n context: ClassDecoratorContext | ClassMethodDecoratorContext,\n) => T) & {\n token: symbol\n schema: ZodType\n}\n\n/**\n * Factory for creating custom attribute decorators.\n * \n * Attributes allow you to add custom metadata to modules, controllers, and endpoints.\n * This is useful for cross-cutting concerns like rate limiting, caching, API versioning, etc.\n * \n * @example\n * ```typescript\n * // Create a simple boolean attribute\n * const Public = AttributeFactory.createAttribute(Symbol.for('Public'))\n * \n * // Use it as a decorator\n * @Controller()\n * @Public()\n * export class PublicController { }\n * \n * // Check if attribute exists\n * if (AttributeFactory.has(Public, controllerMetadata)) {\n * // Skip authentication\n * }\n * ```\n * \n * @example\n * ```typescript\n * // Create an attribute with a validated value\n * const RateLimit = AttributeFactory.createAttribute(\n * Symbol.for('RateLimit'),\n * z.object({ requests: z.number(), window: z.number() })\n * )\n * \n * // Use it with a value\n * @Endpoint(apiEndpoint)\n * @RateLimit({ requests: 100, window: 60000 })\n * async handler() { }\n * \n * // Get the value\n * const limit = AttributeFactory.get(RateLimit, endpointMetadata)\n * // limit is typed as { requests: number, window: number } | null\n * ```\n */\nexport class AttributeFactory {\n /**\n * Creates a simple attribute decorator without a value.\n * \n * @param token - A unique symbol to identify this attribute\n * @returns A decorator function that can be applied to classes or methods\n * \n * @example\n * ```typescript\n * const Public = AttributeFactory.createAttribute(Symbol.for('Public'))\n * \n * @Public()\n * @Controller()\n * export class PublicController { }\n * ```\n */\n static createAttribute(token: symbol): ClassAttribute\n /**\n * Creates an attribute decorator with a validated value.\n * \n * @param token - A unique symbol to identify this attribute\n * @param schema - A Zod schema to validate the attribute value\n * @returns A decorator function that accepts a value and can be applied to classes or methods\n * \n * @example\n * ```typescript\n * const RateLimit = AttributeFactory.createAttribute(\n * Symbol.for('RateLimit'),\n * z.object({ requests: z.number(), window: z.number() })\n * )\n * \n * @RateLimit({ requests: 100, window: 60000 })\n * @Endpoint(apiEndpoint)\n * async handler() { }\n * ```\n */\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 /**\n * Gets the value of an attribute from metadata.\n * \n * Returns `null` if the attribute is not present.\n * For simple attributes (without values), returns `true` if present.\n * \n * @param attribute - The attribute decorator\n * @param target - The metadata object (module, controller, or handler)\n * @returns The attribute value, `true` for simple attributes, or `null` if not found\n * \n * @example\n * ```typescript\n * const isPublic = AttributeFactory.get(Public, controllerMetadata)\n * // isPublic is true | null\n * \n * const rateLimit = AttributeFactory.get(RateLimit, endpointMetadata)\n * // rateLimit is { requests: number, window: number } | null\n * ```\n */\n static get(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): true | null\n static get<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): z.output<T> | null\n static get(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ) {\n return target.customAttributes.get(attribute.token) ?? null\n }\n\n /**\n * Gets all values of an attribute from metadata (useful when an attribute can appear multiple times).\n * \n * Returns `null` if the attribute is not present.\n * \n * @param attribute - The attribute decorator\n * @param target - The metadata object (module, controller, or handler)\n * @returns An array of attribute values, or `null` if not found\n * \n * @example\n * ```typescript\n * const tags = AttributeFactory.getAll(Tag, endpointMetadata)\n * // tags is string[] | null\n * ```\n */\n static getAll(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): Array<true> | null\n static getAll<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): Array<z.output<T>> | null\n static getAll(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\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 /**\n * Gets the last value of an attribute from an array of metadata objects.\n * \n * Searches from the end of the array backwards, useful for finding the most\n * specific attribute value (e.g., endpoint-level overrides module-level).\n * \n * @param attribute - The attribute decorator\n * @param target - An array of metadata objects (typically [module, controller, handler])\n * @returns The last attribute value found, or `null` if not found\n * \n * @example\n * ```typescript\n * // Check attribute hierarchy: endpoint -> controller -> module\n * const rateLimit = AttributeFactory.getLast(RateLimit, [\n * moduleMetadata,\n * controllerMetadata,\n * endpointMetadata\n * ])\n * ```\n */\n static getLast(\n attribute: ClassAttribute,\n target: (ModuleMetadata | ControllerMetadata | HandlerMetadata<any>)[],\n ): true | null\n static getLast<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: (ModuleMetadata | ControllerMetadata | HandlerMetadata<any>)[],\n ): z.output<T> | null\n static getLast(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: (ModuleMetadata | ControllerMetadata | HandlerMetadata<any>)[],\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 /**\n * Checks if an attribute is present on the metadata object.\n * \n * @param attribute - The attribute decorator\n * @param target - The metadata object (module, controller, or handler)\n * @returns `true` if the attribute is present, `false` otherwise\n * \n * @example\n * ```typescript\n * if (AttributeFactory.has(Public, controllerMetadata)) {\n * // Skip authentication\n * }\n * ```\n */\n static has(\n attribute: ClassAttribute,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): boolean\n static has<T extends ZodType>(\n attribute: ClassSchemaAttribute<T>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ): boolean\n static has(\n attribute: ClassAttribute | ClassSchemaAttribute<any>,\n target: ModuleMetadata | ControllerMetadata | HandlerMetadata<any>,\n ) {\n return target.customAttributes.has(attribute.token)\n }\n}\n","import type { AnyInjectableType, InjectionToken } from '@navios/di'\n\nimport { Injectable } from '@navios/di'\n\nexport interface NaviosEnvironmentOptions {\n // Future options can be added here\n httpTokens?: Map<InjectionToken<any, undefined>, AnyInjectableType>\n}\n\n@Injectable()\nexport class NaviosEnvironment {\n private httpTokens = new Map<\n InjectionToken<any, undefined>,\n AnyInjectableType\n >()\n\n setupHttpEnvironment(\n tokens: Map<InjectionToken<any, undefined>, AnyInjectableType>,\n ) {\n this.httpTokens = tokens\n }\n\n getHttpToken(token: InjectionToken<any, undefined>) {\n return this.httpTokens.get(token)\n }\n\n hasHttpSetup() {\n return this.httpTokens.size > 0\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { EndpointAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: EndpointAdapterToken,\n})\nexport class EndpointAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(EndpointAdapterToken)\n if (!service) {\n throw new Error('EndpointAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext } from '@navios/di'\n\nimport { Factory, inject, InjectionToken } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { HttpAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: HttpAdapterToken,\n})\nexport class HttpAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(HttpAdapterToken)\n if (!service) {\n throw new Error('HttpAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { MultipartAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: MultipartAdapterToken,\n})\nexport class MultipartAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(MultipartAdapterToken)\n if (!service) {\n throw new Error('MultipartAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject, InjectableScope } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { Request } from '../tokens/index.mjs'\n\n@Factory({\n token: Request,\n scope: InjectableScope.Request,\n})\nexport class RequestFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(Request)\n if (!service) {\n throw new Error('RequestToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject, InjectableScope } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { Reply } from '../tokens/index.mjs'\n\n@Factory({\n token: Reply,\n scope: InjectableScope.Request,\n})\nexport class ReplyFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(Reply)\n if (!service) {\n throw new Error('ReplyToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { StreamAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: StreamAdapterToken,\n})\nexport class StreamAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(StreamAdapterToken)\n if (!service) {\n throw new Error('StreamAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { FactoryContext, InjectionToken } from '@navios/di'\n\nimport { Factory, inject } from '@navios/di'\n\nimport { NaviosEnvironment } from '../navios.environment.mjs'\nimport { XmlStreamAdapterToken } from '../tokens/index.mjs'\n\n@Factory({\n token: XmlStreamAdapterToken,\n})\nexport class XmlStreamAdapterFactory {\n private readonly environment = inject(NaviosEnvironment)\n create(ctx: FactoryContext) {\n const service = this.environment.getHttpToken(XmlStreamAdapterToken)\n if (!service) {\n throw new Error('XmlStreamAdapterToken service not found in environment')\n }\n return ctx.inject(service as InjectionToken<any, undefined>)\n }\n}\n","import type { ClassTypeWithInstance } from '@navios/di'\n\nimport { Container, inject, Injectable } from '@navios/di'\n\nimport type {\n AbstractHttpAdapterInterface,\n AbstractHttpListenOptions,\n NaviosModule,\n PluginContext,\n PluginDefinition,\n} from './interfaces/index.mjs'\nimport type { LoggerService, LogLevel } from './logger/index.mjs'\nimport type { NaviosEnvironmentOptions } from './navios.environment.mjs'\n\nimport { HttpAdapterToken } from './index.mjs'\nimport { Logger } from './logger/index.mjs'\nimport { NaviosEnvironment } from './navios.environment.mjs'\nimport { ModuleLoaderService } from './services/index.mjs'\n\n/**\n * Options for configuring the Navios application context.\n * These options control dependency injection and logging behavior.\n */\nexport interface NaviosApplicationContextOptions {\n /**\n * Specifies the logger to use. Pass `false` to turn off logging.\n *\n * - `LoggerService` instance: Use a custom logger implementation\n * - `LogLevel[]`: Enable specific log levels (e.g., ['error', 'warn', 'log'])\n * - `false`: Disable logging completely\n */\n logger?: LoggerService | LogLevel[] | false\n\n /**\n * Specifies a custom container to use. Useful for testing.\n * If not provided, a new Container will be created.\n */\n container?: Container\n}\n\n/**\n * Complete options for creating a Navios application.\n * Extends NaviosApplicationContextOptions with adapter configuration.\n */\nexport interface NaviosApplicationOptions extends NaviosApplicationContextOptions {\n /**\n * HTTP adapter environment(s) to use for the application.\n * Can be a single adapter or an array of adapters.\n *\n * @example\n * ```typescript\n * adapter: defineFastifyEnvironment()\n * // or\n * adapter: [defineFastifyEnvironment(), defineBunEnvironment()]\n * ```\n */\n adapter: NaviosEnvironmentOptions | NaviosEnvironmentOptions[]\n\n /**\n * Whether to validate response schemas.\n * When `false`, response schema validation is skipped for better performance.\n * @default true\n */\n validateResponses?: boolean\n\n /**\n * Whether to enable request ID propagation via AsyncLocalStorage.\n * When `true`, request IDs are available via `getRequestId()` throughout the request.\n * @default false\n */\n enableRequestId?: boolean\n}\n\n/**\n * Main application class for Navios.\n *\n * This class represents a Navios application instance and provides methods\n * for initializing, configuring, and managing the HTTP server.\n *\n * @example\n * ```typescript\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * })\n *\n * app.setGlobalPrefix('/api')\n * app.enableCors({ origin: ['http://localhost:3000'] })\n * await app.init()\n * await app.listen({ port: 3000, host: '0.0.0.0' })\n * ```\n */\n@Injectable()\nexport class NaviosApplication {\n private environment = inject(NaviosEnvironment)\n private moduleLoader = inject(ModuleLoaderService)\n private httpApplication: AbstractHttpAdapterInterface<any> | null = null\n private logger = inject(Logger, {\n context: NaviosApplication.name,\n })\n protected container = inject(Container)\n\n private appModule: ClassTypeWithInstance<NaviosModule> | null = null\n private options: NaviosApplicationOptions = {\n adapter: [],\n }\n private plugins: PluginDefinition<any>[] = []\n\n /**\n * Indicates whether the application has been initialized.\n * Set to `true` after `init()` completes successfully.\n */\n isInitialized = false\n\n /**\n * Sets up the application with the provided module and options.\n * This is called automatically by NaviosFactory.create().\n *\n * @param appModule - The root application module\n * @param options - Application configuration options\n * @internal\n */\n async setup(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: NaviosApplicationOptions = {\n adapter: [],\n },\n ) {\n this.appModule = appModule\n this.options = options\n if (this.environment.hasHttpSetup()) {\n this.httpApplication = await this.container.get(HttpAdapterToken)\n }\n }\n\n /**\n * Gets the dependency injection container used by this application.\n *\n * @returns The Container instance\n */\n getContainer() {\n return this.container\n }\n\n /**\n * Registers a plugin to be initialized after modules are loaded.\n *\n * Plugins are initialized in the order they are registered,\n * after all modules are loaded but before the server starts listening.\n *\n * @param definition - Plugin definition with options\n * @returns this for method chaining\n *\n * @example\n * ```typescript\n * import { defineOpenApiPlugin } from '@navios/openapi-fastify'\n *\n * app.usePlugin(defineOpenApiPlugin({\n * info: { title: 'My API', version: '1.0.0' },\n * }))\n * ```\n */\n usePlugin<TOptions>(definition: PluginDefinition<TOptions>): this {\n this.plugins.push(definition)\n return this\n }\n\n /**\n * Initializes the application.\n *\n * This method:\n * - Loads all modules and their dependencies\n * - Sets up the HTTP server if an adapter is configured\n * - Calls onModuleInit hooks on all modules\n * - Initializes registered plugins\n * - Marks the application as initialized\n *\n * Must be called before `listen()`.\n *\n * @throws Error if app module is not set\n *\n * @example\n * ```typescript\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * })\n * await app.init()\n * await app.listen({ port: 3000 })\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 if (this.environment.hasHttpSetup()) {\n await this.httpApplication?.setupHttpServer(this.options)\n }\n await this.initPlugins()\n await this.initModules()\n if (this.environment.hasHttpSetup()) {\n await this.httpApplication?.ready()\n }\n\n this.isInitialized = true\n this.logger.debug('Navios application initialized')\n }\n\n private async initModules() {\n const modules = this.moduleLoader.getAllModules()\n await this.httpApplication?.onModulesInit(modules)\n }\n\n private async initPlugins() {\n if (this.plugins.length === 0) return\n\n let server: any = null\n try {\n server = this.httpApplication?.getServer() ?? null\n } catch {\n // ignore\n }\n const context: PluginContext = {\n modules: this.moduleLoader.getAllModules(),\n server,\n container: this.container,\n globalPrefix: this.httpApplication?.getGlobalPrefix() ?? '',\n moduleLoader: this.moduleLoader,\n }\n\n for (const { plugin, options } of this.plugins) {\n this.logger.debug(`Initializing plugin: ${plugin.name}`)\n await plugin.register(context, options)\n }\n }\n\n /**\n * Enables CORS (Cross-Origin Resource Sharing) for the application.\n *\n * @param options - CORS configuration options (adapter-specific)\n * @throws Error if HTTP application is not set\n *\n * @example\n * ```typescript\n * app.enableCors({\n * origin: ['http://localhost:3000', 'https://example.com'],\n * methods: ['GET', 'POST', 'PUT', 'DELETE'],\n * credentials: true,\n * })\n * ```\n */\n enableCors(options: any) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n this.httpApplication.enableCors(options)\n }\n\n /**\n * Enables multipart/form-data support for file uploads.\n *\n * @param options - Multipart configuration options (adapter-specific)\n * @throws Error if HTTP application is not set\n *\n * @example\n * ```typescript\n * app.enableMultipart({\n * limits: {\n * fileSize: 1024 * 1024 * 10, // 10MB\n * },\n * })\n * ```\n */\n enableMultipart(options: any) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n this.httpApplication.enableMultipart(options)\n }\n\n /**\n * Sets a global prefix for all routes.\n *\n * @param prefix - The prefix to prepend to all route URLs (e.g., '/api')\n * @throws Error if HTTP application is not set\n *\n * @example\n * ```typescript\n * app.setGlobalPrefix('/api/v1')\n * // All routes will be prefixed with /api/v1\n * ```\n */\n setGlobalPrefix(prefix: string) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n this.httpApplication.setGlobalPrefix(prefix)\n }\n\n /**\n * Gets the underlying HTTP server instance.\n *\n * The type of the returned server depends on the adapter used:\n * - Fastify adapter: Returns FastifyInstance\n * - Bun adapter: Returns Bun.Server\n *\n * @returns The HTTP server instance\n * @throws Error if HTTP application is not set\n *\n * @example\n * ```typescript\n * const server = app.getServer()\n * // Use adapter-specific server methods\n * ```\n */\n getServer() {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n return this.httpApplication.getServer()\n }\n\n /**\n * Starts the HTTP server and begins listening for requests.\n *\n * @param options - Listen options (port, host, etc.)\n * @throws Error if HTTP application is not set\n *\n * @example\n * ```typescript\n * await app.listen({ port: 3000, host: '0.0.0.0' })\n * ```\n */\n async listen(options: AbstractHttpListenOptions) {\n if (!this.httpApplication) {\n throw new Error('HTTP application is not set')\n }\n await this.httpApplication.listen(options)\n }\n\n /**\n * Disposes of application resources.\n *\n * Cleans up the HTTP server and module loader.\n * This method is called automatically by `close()`.\n */\n async dispose() {\n if (this.httpApplication) {\n await this.httpApplication.dispose()\n }\n if (this.moduleLoader) {\n this.moduleLoader.dispose()\n }\n }\n\n /**\n * Closes the application and cleans up all resources.\n *\n * This is an alias for `dispose()`.\n *\n * @example\n * ```typescript\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await app.close()\n * process.exit(0)\n * })\n * ```\n */\n async close() {\n await this.dispose()\n }\n}\n","import type {\n AnyInjectableType,\n ClassTypeWithInstance,\n InjectionToken,\n} from '@navios/di'\n\nimport { Container, InjectableScope, InjectableType } from '@navios/di'\n\nimport type { NaviosModule } from './interfaces/index.mjs'\nimport type {\n NaviosApplicationContextOptions,\n NaviosApplicationOptions,\n} from './navios.application.mjs'\n\nimport { ConsoleLogger, isNil, LoggerOutput } from './logger/index.mjs'\nimport { NaviosApplication } from './navios.application.mjs'\nimport { NaviosEnvironment } from './navios.environment.mjs'\nimport { setRequestIdEnabled } from './stores/index.mjs'\nimport { NaviosOptionsToken } from './tokens/index.mjs'\n\n/**\n * Factory class for creating and configuring Navios applications.\n *\n * This is the main entry point for bootstrapping a Navios application.\n * It handles dependency injection container setup, adapter registration,\n * and logger configuration.\n *\n * @example\n * ```typescript\n * import { NaviosFactory } from '@navios/core'\n * import { defineFastifyEnvironment } from '@navios/adapter-fastify'\n *\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * logger: ['log', 'error', 'warn'],\n * })\n *\n * await app.init()\n * await app.listen({ port: 3000 })\n * ```\n */\nexport class NaviosFactory {\n /**\n * Creates a new Navios application instance.\n *\n * This method sets up the dependency injection container, registers the HTTP adapter,\n * configures logging, and initializes the application with the provided module.\n *\n * @param appModule - The root application module class decorated with @Module()\n * @param options - Configuration options for the application\n * @param options.adapter - HTTP adapter environment (required for HTTP server functionality)\n * @param options.logger - Logger configuration. Can be:\n * - A LoggerService instance for custom logging\n * - An array of LogLevel strings to enable specific log levels\n * - `false` to disable logging\n * @param options.container - Optional custom dependency injection container (useful for testing)\n * @returns A configured NaviosApplication instance ready to be initialized\n *\n * @example\n * ```typescript\n * // Basic setup with Fastify adapter\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * })\n *\n * // With custom logger configuration\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * logger: ['error', 'warn', 'log'],\n * })\n *\n * // With custom container for testing\n * const container = new Container()\n * const app = await NaviosFactory.create(AppModule, {\n * adapter: defineFastifyEnvironment(),\n * container,\n * })\n * ```\n */\n static async create(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: NaviosApplicationOptions = {\n adapter: [],\n },\n ) {\n const container = options.container ?? new Container()\n\n // Set request ID flag early, before any adapters are registered\n if (options.enableRequestId === true) {\n setRequestIdEnabled(true)\n }\n\n // Store options in container for DI access by adapters\n container\n .getServiceLocator()\n .getManager()\n .storeCreatedHolder(\n NaviosOptionsToken.toString(),\n options,\n InjectableType.Class,\n InjectableScope.Singleton,\n )\n\n await this.registerLoggerConfiguration(container, options)\n const adapters = Array.isArray(options.adapter)\n ? options.adapter\n : [options.adapter]\n for (const adapter of adapters) {\n await this.registerEnvironment(container, adapter)\n }\n const app = await container.get(NaviosApplication)\n await app.setup(appModule, options)\n return app\n }\n\n private static async registerEnvironment(\n container: Container,\n environment: {\n httpTokens?: Map<InjectionToken<any, undefined>, AnyInjectableType>\n } = {},\n ) {\n const naviosEnvironment = await container.get(NaviosEnvironment)\n const { httpTokens } = environment\n if (httpTokens) {\n naviosEnvironment.setupHttpEnvironment(httpTokens)\n }\n }\n\n private static async registerLoggerConfiguration(\n container: Container,\n options: NaviosApplicationContextOptions,\n ) {\n const { logger } = options\n if (Array.isArray(logger) || isNil(logger)) {\n const loggerInstance = (await container.get(\n LoggerOutput,\n )) as ConsoleLogger\n loggerInstance?.setup({\n logLevels: logger,\n })\n return\n }\n if ((logger as boolean) !== true && !isNil(logger)) {\n container\n .getServiceLocator()\n .getManager()\n .storeCreatedHolder(\n LoggerOutput.toString(),\n logger,\n InjectableType.Class,\n InjectableScope.Singleton,\n )\n }\n }\n}\n","import { $ as LOG_LEVELS, A as Logger, B as isFunction, C as EnvConfigProvider, D as _ConfigService, E as ConfigServiceToken, F as runWithRequestId, G as isString, H as isNumber, I as setRequestIdEnabled, J as normalizePath, K as isSymbol, L as addLeadingSlash, M as loggerOptionsSchema, N as generateRequestId, O as _LoggerInstance, P as getRequestId, Q as isLogLevel, R as isConstructor, S as ConfigProviderOptions, T as ConfigServiceOptionsSchema, U as isObject, V as isNil, W as isPlainObject, X as isLogLevelEnabled, Y as stripEndSlash, Z as filterLogLevels, _ as NotFoundException, a as _ReplyFactory, b as BadRequestException, c as _HttpAdapterFactory, d as _ModuleLoaderService, et as clc, f as _GuardRunnerService, g as UnauthorizedException, h as ConflictException, i as _StreamAdapterFactory, j as LoggerOutput, k as _ConsoleLogger, l as _EndpointAdapterFactory, m as _InstanceResolverService, n as _NaviosApplication, nt as envInt, o as _RequestFactory, p as ControllerResolverService, q as isUndefined, r as _XmlStreamAdapterFactory, rt as envString, s as _MultipartAdapterFactory, t as NaviosFactory, tt as yellow, u as AttributeFactory, v as InternalServerErrorException, w as provideConfig, x as HttpException, y as ForbiddenException, z as isEmpty } from \"./src-gBAChVRL.mjs\";\nimport { C as ControllerMetadataKey, D as EndpointMetadataKey, E as hasControllerMetadata, O as getAllEndpointMetadata, S as hasModuleMetadata, T as getControllerMetadata, _ as EndpointAdapterToken, a as HttpCode, b as extractModuleMetadata, c as XmlStreamAdapterToken, d as Reply, f as NaviosOptionsToken, g as ExecutionContextInjectionToken, h as ExecutionContext, i as Module, k as getEndpointMetadata, l as StreamAdapterToken, m as HttpAdapterToken, n as Stream, o as Header, p as MultipartAdapterToken, r as Multipart, s as Endpoint, t as UseGuards, u as Request, v as Controller, w as extractControllerMetadata, x as getModuleMetadata, y as ModuleMetadataKey } from \"./use-guards.decorator-CUww54Nt.mjs\";\n\nexport * from \"@navios/di\"\n\nexport { AttributeFactory, BadRequestException, ConfigProviderOptions, _ConfigService as ConfigService, ConfigServiceOptionsSchema, ConfigServiceToken, ConflictException, _ConsoleLogger as ConsoleLogger, Controller, ControllerMetadataKey, ControllerResolverService, Endpoint, _EndpointAdapterFactory as EndpointAdapterFactory, EndpointAdapterToken, EndpointMetadataKey, EnvConfigProvider, ExecutionContext, ExecutionContextInjectionToken, ForbiddenException, _GuardRunnerService as GuardRunnerService, Header, _HttpAdapterFactory as HttpAdapterFactory, HttpAdapterToken, HttpCode, HttpException, _InstanceResolverService as InstanceResolverService, InternalServerErrorException, LOG_LEVELS, Logger, _LoggerInstance as LoggerInstance, LoggerOutput, Module, _ModuleLoaderService as ModuleLoaderService, ModuleMetadataKey, Multipart, _MultipartAdapterFactory as MultipartAdapterFactory, MultipartAdapterToken, _NaviosApplication as NaviosApplication, NaviosFactory, NaviosOptionsToken, NotFoundException, Reply, _ReplyFactory as ReplyFactory, Request, _RequestFactory as RequestFactory, Stream, _StreamAdapterFactory as StreamAdapterFactory, StreamAdapterToken, UnauthorizedException, UseGuards, _XmlStreamAdapterFactory as XmlStreamAdapterFactory, XmlStreamAdapterToken, addLeadingSlash, clc, envInt, envString, extractControllerMetadata, extractModuleMetadata, filterLogLevels, generateRequestId, getAllEndpointMetadata, getControllerMetadata, getEndpointMetadata, getModuleMetadata, getRequestId, hasControllerMetadata, hasModuleMetadata, isConstructor, isEmpty, isFunction, isLogLevel, isLogLevelEnabled, isNil, isNumber, isObject, isPlainObject, isString, isSymbol, isUndefined, loggerOptionsSchema, normalizePath, provideConfig, runWithRequestId, setRequestIdEnabled, stripEndSlash, yellow };","import type { CommandMetadata } from '../metadata/command.metadata.mjs'\n\n/**\n * Execution context for a command execution.\n *\n * Provides access to command metadata, path, and validated options during command execution.\n * This context is automatically injected and available via the `CommandExecutionContext` token.\n *\n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/di'\n * import { CommandExecutionContext } from '@navios/commander'\n *\n * @Injectable()\n * class CommandLogger {\n * private ctx = inject(CommandExecutionContext)\n *\n * log() {\n * console.log('Command:', this.ctx.getCommandPath())\n * console.log('Options:', this.ctx.getOptions())\n * }\n * }\n * ```\n */\nexport class CommanderExecutionContext {\n /**\n * @internal\n * Creates a new execution context.\n */\n constructor(\n private readonly command: CommandMetadata,\n private readonly commandPath: string,\n private readonly options: any,\n ) {}\n\n /**\n * Gets the command metadata.\n *\n * @returns The command metadata including path and options schema\n */\n getCommand(): CommandMetadata {\n return this.command\n }\n\n /**\n * Gets the command path that was invoked.\n *\n * @returns The command path (e.g., 'greet', 'user:create')\n */\n getCommandPath(): string {\n return this.commandPath\n }\n\n /**\n * Gets the validated command options.\n *\n * Options are validated against the command's Zod schema if one was provided.\n *\n * @returns The validated options object\n */\n getOptions(): any {\n return this.options\n }\n}\n","import type { ClassType } from '@navios/core'\nimport type { ZodObject } from 'zod'\n\n/**\n * @internal\n * Symbol key used to store command metadata on classes.\n */\nexport const CommandMetadataKey = Symbol('CommandMetadataKey')\n\n/**\n * Metadata associated with a command.\n *\n * @public\n */\nexport interface CommandMetadata {\n /**\n * The command path (e.g., 'greet', 'user:create').\n */\n path: string\n /**\n * Optional Zod schema for validating command options.\n */\n optionsSchema?: ZodObject\n /**\n * Map of custom attributes that can be attached to the command.\n */\n customAttributes: Map<string | symbol, any>\n}\n\n/**\n * Gets or creates command metadata for a class.\n *\n * @internal\n * @param target - The command class\n * @param context - The decorator context\n * @param path - The command path\n * @param optionsSchema - Optional Zod schema\n * @returns The command metadata\n */\nexport function getCommandMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n path: string,\n optionsSchema?: ZodObject,\n): CommandMetadata {\n if (context.metadata) {\n const metadata = context.metadata[CommandMetadataKey] as\n | CommandMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const newMetadata: CommandMetadata = {\n path,\n optionsSchema,\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[CommandMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[CommandMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios Commander] Wrong environment.')\n}\n\n/**\n * Extracts command metadata from a class.\n *\n * @param target - The command class\n * @returns The command metadata\n * @throws {Error} If the class is not decorated with @Command\n *\n * @example\n * ```typescript\n * const metadata = extractCommandMetadata(GreetCommand)\n * console.log(metadata.path) // 'greet'\n * ```\n */\nexport function extractCommandMetadata(target: ClassType): CommandMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CommandMetadataKey] as CommandMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios Commander] Command metadata not found. Make sure to use @Command decorator.',\n )\n }\n return metadata\n}\n\n/**\n * Checks if a class has command metadata.\n *\n * @param target - The class to check\n * @returns `true` if the class is decorated with @Command, `false` otherwise\n */\nexport function hasCommandMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CommandMetadataKey] as CommandMetadata | undefined\n return !!metadata\n}\n","import type { ClassType } from '@navios/core'\n\n/**\n * @internal\n * Symbol key used to store CLI module metadata on classes.\n */\nexport const CliModuleMetadataKey = Symbol('CliModuleMetadataKey')\n\n/**\n * Metadata associated with a CLI module.\n *\n * @public\n */\nexport interface CliModuleMetadata {\n /**\n * Set of command classes registered in this module.\n */\n commands: Set<ClassType>\n /**\n * Set of other modules imported by this module.\n */\n imports: Set<ClassType>\n /**\n * Map of custom attributes that can be attached to the module.\n */\n customAttributes: Map<string | symbol, any>\n}\n\n/**\n * Gets or creates CLI module metadata for a class.\n *\n * @internal\n * @param target - The module class\n * @param context - The decorator context\n * @returns The module metadata\n */\nexport function getCliModuleMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): CliModuleMetadata {\n if (context.metadata) {\n const metadata = context.metadata[CliModuleMetadataKey] as\n | CliModuleMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const newMetadata: CliModuleMetadata = {\n commands: new Set<ClassType>(),\n imports: new Set<ClassType>(),\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[CliModuleMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[CliModuleMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios Commander] Wrong environment.')\n}\n\n/**\n * Extracts CLI module metadata from a class.\n *\n * @param target - The module class\n * @returns The module metadata\n * @throws {Error} If the class is not decorated with @CliModule\n *\n * @example\n * ```typescript\n * const metadata = extractCliModuleMetadata(AppModule)\n * console.log(metadata.commands.size) // Number of commands\n * ```\n */\nexport function extractCliModuleMetadata(target: ClassType): CliModuleMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CliModuleMetadataKey] as CliModuleMetadata | undefined\n if (!metadata) {\n throw new Error(\n `[Navios Commander] Module metadata not found for ${target.name}. Make sure to use @CliModule decorator.`,\n )\n }\n return metadata\n}\n\n/**\n * Checks if a class has CLI module metadata.\n *\n * @param target - The class to check\n * @returns `true` if the class is decorated with @CliModule, `false` otherwise\n */\nexport function hasCliModuleMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n return !!target[CliModuleMetadataKey]\n}\n","import type { ClassTypeWithInstance, NaviosModule } from '@navios/core'\n\nimport { Container, inject, Injectable } from '@navios/core'\n\nimport type { CommandHandler } from '../interfaces/index.mjs'\nimport type { CliModuleMetadata, CommandMetadata } from '../metadata/index.mjs'\n\nimport {\n extractCliModuleMetadata,\n extractCommandMetadata,\n} from '../metadata/index.mjs'\n\n/**\n * Command class with its associated metadata.\n *\n * @public\n */\nexport interface CommandWithMetadata {\n /**\n * The command class constructor.\n */\n class: ClassTypeWithInstance<CommandHandler>\n /**\n * The command metadata including path and options schema.\n */\n metadata: CommandMetadata\n}\n\n/**\n * Service for loading and managing CLI modules and commands.\n *\n * Handles module traversal, command registration, and metadata collection.\n * This service is used internally by CommanderApplication.\n *\n * @public\n */\n@Injectable()\nexport class CliModuleLoaderService {\n protected container = inject(Container)\n private modulesMetadata: Map<string, CliModuleMetadata> = new Map()\n private loadedModules: Map<string, any> = new Map()\n private commandsMetadata: Map<string, CommandWithMetadata> = new Map()\n private initialized = false\n\n /**\n * Loads all modules starting from the root app module.\n *\n * Traverses the module tree, loads imported modules, and collects command metadata.\n *\n * @param appModule - The root CLI module\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?: CliModuleMetadata,\n ) {\n const metadata = extractCliModuleMetadata(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\n // Collect command metadata during module loading\n for (const command of metadata.commands) {\n const commandMetadata = extractCommandMetadata(command)\n this.commandsMetadata.set(commandMetadata.path, {\n class: command,\n metadata: commandMetadata,\n })\n }\n\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 this.container.get(module)\n if (instance.onModuleInit) {\n await instance.onModuleInit()\n }\n this.loadedModules.set(moduleName, instance)\n }\n\n private mergeMetadata(\n metadata: CliModuleMetadata,\n parentMetadata: CliModuleMetadata,\n ): void {\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\n /**\n * Gets all loaded module metadata.\n *\n * @returns Map of module names to their metadata\n */\n getAllModules(): Map<string, CliModuleMetadata> {\n return this.modulesMetadata\n }\n\n /**\n * Gets all command classes indexed by command class name.\n *\n * @returns Map of command class names to command classes\n */\n getAllCommands(): Map<string, ClassTypeWithInstance<any>> {\n const commands = new Map<string, ClassTypeWithInstance<any>>()\n for (const metadata of this.modulesMetadata.values()) {\n for (const command of metadata.commands) {\n commands.set(command.name, command)\n }\n }\n return commands\n }\n\n /**\n * Get all commands with their metadata, indexed by command path.\n * This is populated during loadModules, so path information is available\n * before parsing CLI argv.\n */\n getAllCommandsWithMetadata(): Map<string, CommandWithMetadata> {\n return this.commandsMetadata\n }\n\n /**\n * Get a command by its path, with metadata already extracted.\n * Returns undefined if command is not found.\n */\n getCommandByPath(path: string): CommandWithMetadata | undefined {\n return this.commandsMetadata.get(path)\n }\n\n /**\n * Disposes of all loaded modules and commands, clearing internal state.\n */\n dispose() {\n this.modulesMetadata.clear()\n this.loadedModules.clear()\n this.commandsMetadata.clear()\n this.initialized = false\n }\n}\n","import type { ZodObject, ZodType } from 'zod'\n\nimport { Injectable } from '@navios/core'\n\n/**\n * Result of parsing command-line arguments.\n *\n * @public\n */\nexport interface ParsedCliArgs {\n /**\n * The command path (e.g., 'greet', 'user:create').\n * Multi-word commands are joined with spaces.\n */\n command: string\n /**\n * Parsed options as key-value pairs.\n * Keys are converted from kebab-case to camelCase.\n */\n options: Record<string, any>\n /**\n * Positional arguments that don't match any option flags.\n */\n positionals: string[]\n}\n\n/**\n * Service for parsing command-line arguments.\n *\n * Handles parsing of various CLI argument formats including:\n * - Long options: `--key value` or `--key=value`\n * - Short options: `-k value` or `-abc` (multiple flags)\n * - Boolean flags\n * - Array options\n * - Positional arguments\n *\n * @public\n */\n@Injectable()\nexport class CliParserService {\n /**\n * Parses command-line arguments from process.argv\n * Commands can be multi-word (e.g., 'db migrate', 'cache clear')\n * Expected format: node script.js command [subcommand...] --flag value --boolean-flag positional1 positional2\n *\n * @param argv - Array of command-line arguments (typically process.argv)\n * @param optionsSchema - Optional Zod schema to determine boolean flags and option types\n * @returns Parsed command (space-separated if multi-word), options, and positional arguments\n */\n parse(argv: string[], optionsSchema?: ZodObject): ParsedCliArgs {\n // Skip first two args (node and script path)\n const args = argv.slice(2)\n\n if (args.length === 0) {\n throw new Error('[Navios Commander] No command provided')\n }\n\n // Extract boolean and array field names from schema for accurate parsing\n const booleanFields = optionsSchema\n ? this.extractBooleanFields(optionsSchema)\n : new Set<string>()\n const arrayFields = optionsSchema\n ? this.extractArrayFields(optionsSchema)\n : new Set<string>()\n\n // Collect command words until we hit an argument that starts with '-' or '--'\n const commandParts: string[] = []\n let i = 0\n while (i < args.length && !args[i].startsWith('-')) {\n commandParts.push(args[i])\n i++\n }\n\n if (commandParts.length === 0) {\n throw new Error('[Navios Commander] No command provided')\n }\n\n const command = commandParts.join(' ')\n const options: Record<string, any> = {}\n const positionals: string[] = []\n while (i < args.length) {\n const arg = args[i]\n\n if (arg.startsWith('--')) {\n // Long option format: --key=value or --key value\n const key = arg.slice(2)\n const equalIndex = key.indexOf('=')\n\n if (equalIndex !== -1) {\n // Format: --key=value\n const optionName = key.slice(0, equalIndex)\n const optionValue = key.slice(equalIndex + 1)\n const camelCaseKey = this.camelCase(optionName)\n const isArray =\n arrayFields.has(camelCaseKey) || arrayFields.has(optionName)\n\n if (isArray) {\n // For array fields, accumulate values\n if (!options[camelCaseKey]) {\n options[camelCaseKey] = []\n }\n options[camelCaseKey].push(this.parseValue(optionValue))\n } else {\n options[camelCaseKey] = this.parseValue(optionValue)\n }\n i++\n } else {\n // Format: --key value or --boolean-flag\n const camelCaseKey = this.camelCase(key)\n const isBoolean =\n booleanFields.has(camelCaseKey) || booleanFields.has(key)\n const isArray = arrayFields.has(camelCaseKey) || arrayFields.has(key)\n const nextArg = args[i + 1]\n\n if (isBoolean) {\n // Known boolean flag from schema\n options[camelCaseKey] = true\n i++\n } else if (isArray && nextArg && !nextArg.startsWith('-')) {\n // Known array field from schema - accumulate values\n if (!options[camelCaseKey]) {\n options[camelCaseKey] = []\n }\n options[camelCaseKey].push(this.parseValue(nextArg))\n i += 2\n } else if (nextArg && !nextArg.startsWith('-')) {\n // Has a value\n options[camelCaseKey] = this.parseValue(nextArg)\n i += 2\n } else {\n // Assume boolean flag\n options[camelCaseKey] = true\n i++\n }\n }\n } else if (arg.startsWith('-') && arg.length > 1 && arg !== '-') {\n // Short option format: -k value or -abc (multiple flags)\n const flags = arg.slice(1)\n\n if (flags.length === 1) {\n // Single short flag: -k value or -k\n const isBoolean = booleanFields.has(flags)\n const isArray = arrayFields.has(flags)\n const nextArg = args[i + 1]\n\n if (isBoolean) {\n // Known boolean flag from schema\n options[flags] = true\n i++\n } else if (isArray && nextArg && !nextArg.startsWith('-')) {\n // Known array field from schema - accumulate values\n if (!options[flags]) {\n options[flags] = []\n }\n options[flags].push(this.parseValue(nextArg))\n i += 2\n } else if (nextArg && !nextArg.startsWith('-')) {\n options[flags] = this.parseValue(nextArg)\n i += 2\n } else {\n options[flags] = true\n i++\n }\n } else {\n // Multiple short flags: -abc -> {a: true, b: true, c: true}\n for (const flag of flags) {\n options[flag] = true\n }\n i++\n }\n } else {\n // Positional argument\n positionals.push(arg)\n i++\n }\n }\n\n return {\n command,\n options,\n positionals,\n }\n }\n\n /**\n * Converts kebab-case to camelCase\n */\n private camelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())\n }\n\n /**\n * Attempts to parse string values into appropriate types\n */\n private parseValue(value: string): any {\n // Check for boolean\n if (value === 'true') return true\n if (value === 'false') return false\n\n // Check for null/undefined\n if (value === 'null') return null\n if (value === 'undefined') return undefined\n\n // Check for number\n if (/^-?\\d+$/.test(value)) {\n return parseInt(value, 10)\n }\n if (/^-?\\d+\\.\\d+$/.test(value)) {\n return parseFloat(value)\n }\n\n // Check for JSON\n if (\n (value.startsWith('{') && value.endsWith('}')) ||\n (value.startsWith('[') && value.endsWith(']'))\n ) {\n try {\n return JSON.parse(value)\n } catch {\n // If parsing fails, return as string\n return value\n }\n }\n\n // Return as string\n return value\n }\n\n /**\n * Extracts boolean field names from a Zod schema\n * Handles ZodObject, ZodOptional, and ZodDefault wrappers\n */\n private extractBooleanFields(schema: ZodObject): Set<string> {\n const booleanFields = new Set<string>()\n\n try {\n // Check if schema has _def.typeName (Zod schema structure)\n const typeName = schema.def.type\n\n if (typeName === 'object') {\n // Extract shape from ZodObject\n const shape = schema.def.shape\n\n if (shape && typeof shape === 'object') {\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (this.isSchemaBoolean(fieldSchema as any)) {\n booleanFields.add(key)\n }\n }\n }\n }\n } catch {\n // Silently fail if schema introspection fails\n }\n\n return booleanFields\n }\n\n /**\n * Extracts array field names from a Zod schema\n * Handles ZodObject, ZodOptional, and ZodDefault wrappers\n */\n private extractArrayFields(schema: ZodObject): Set<string> {\n const arrayFields = new Set<string>()\n\n try {\n const typeName = schema.def.type\n\n if (typeName === 'object') {\n const shape = schema.def.shape\n\n if (shape && typeof shape === 'object') {\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (this.isSchemaArray(fieldSchema as any)) {\n arrayFields.add(key)\n }\n }\n }\n }\n } catch {\n // Silently fail if schema introspection fails\n }\n\n return arrayFields\n }\n\n /**\n * Checks if a Zod schema represents a boolean type\n * Unwraps ZodOptional and ZodDefault\n */\n private isSchemaBoolean(schema: ZodType): boolean {\n try {\n let currentSchema = schema\n const typeName = currentSchema.def.type\n\n // Unwrap ZodOptional and ZodDefault\n if (typeName === 'optional' || typeName === 'default') {\n currentSchema = (currentSchema as any)?._def?.innerType || currentSchema\n }\n\n const innerTypeName = currentSchema.def.type\n return innerTypeName === 'boolean'\n } catch {\n return false\n }\n }\n\n /**\n * Checks if a Zod schema represents an array type\n * Unwraps ZodOptional and ZodDefault\n */\n private isSchemaArray(schema: ZodType): boolean {\n try {\n let currentSchema = schema\n const typeName = currentSchema.def.type\n\n // Unwrap ZodOptional and ZodDefault\n if (typeName === 'optional' || typeName === 'default') {\n currentSchema = (currentSchema as any)?._def?.innerType || currentSchema\n }\n\n const innerTypeName = currentSchema.def.type\n return innerTypeName === 'array'\n } catch {\n return false\n }\n }\n\n /**\n * Formats help text listing all available commands.\n *\n * @param commands - Array of command objects with path and class\n * @returns Formatted string listing all commands\n */\n formatCommandList(commands: Array<{ path: string; class: any }>): string {\n const lines = ['Available commands:', '']\n for (const { path } of commands) {\n lines.push(` ${path}`)\n }\n return lines.join('\\n')\n }\n}\n","import { InjectionToken } from '@navios/core'\n\nimport type { CommanderExecutionContext } from '../interfaces/index.mjs'\n\nconst CommandExecutionContextInjectionToken =\n 'CommanderExecutionContextInjectionToken'\n\n/**\n * Injection token for accessing the current command execution context.\n *\n * Use this token with `inject()` to access the `CommanderExecutionContext` in services\n * that need information about the currently executing command.\n *\n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/di'\n * import { CommandExecutionContext } from '@navios/commander'\n *\n * @Injectable()\n * class MyService {\n * private ctx = inject(CommandExecutionContext)\n *\n * doSomething() {\n * const commandPath = this.ctx.getCommandPath()\n * const options = this.ctx.getOptions()\n * // Use context information...\n * }\n * }\n * ```\n */\nexport const CommandExecutionContext =\n InjectionToken.create<CommanderExecutionContext>(\n CommandExecutionContextInjectionToken,\n )\n","import type {\n ClassTypeWithInstance,\n InjectionToken,\n NaviosModule,\n} from '@navios/core'\n\nimport { Container, inject, Injectable } from '@navios/core'\n\nimport type { CommandHandler } from './interfaces/index.mjs'\n\nimport { CommanderExecutionContext } from './interfaces/index.mjs'\nimport { CliModuleLoaderService, CliParserService } from './services/index.mjs'\nimport { CommandExecutionContext } from './tokens/index.mjs'\n\n/**\n * Configuration options for CommanderApplication.\n *\n * @public\n */\nexport interface CommanderApplicationOptions {}\n\n/**\n * Main application class for managing CLI command execution.\n *\n * This class handles module loading, command registration, and command execution.\n * It provides both programmatic and CLI-based command execution capabilities.\n *\n * @example\n * ```typescript\n * const app = await CommanderFactory.create(AppModule)\n * await app.init()\n * await app.run(process.argv)\n * ```\n */\n@Injectable()\nexport class CommanderApplication {\n private moduleLoader = inject(CliModuleLoaderService)\n private cliParser = inject(CliParserService)\n protected container = inject(Container)\n\n private appModule: ClassTypeWithInstance<NaviosModule> | null = null\n private options: CommanderApplicationOptions = {}\n\n /**\n * Indicates whether the application has been initialized.\n * Set to `true` after `init()` is called successfully.\n */\n isInitialized = false\n\n /**\n * @internal\n * Sets up the application with the provided module and options.\n * This is called automatically by CommanderFactory.create().\n */\n async setup(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: CommanderApplicationOptions = {},\n ) {\n this.appModule = appModule\n this.options = options\n }\n\n /**\n * Gets the dependency injection container used by this application.\n *\n * @returns The Container instance\n *\n * @example\n * ```typescript\n * const container = app.getContainer()\n * const service = await container.get(MyService)\n * ```\n */\n getContainer() {\n return this.container\n }\n\n /**\n * Initializes the application by loading all modules and registering commands.\n *\n * This method must be called before executing commands or running the CLI.\n * It traverses the module tree, loads all imported modules, and collects command metadata.\n *\n * @throws {Error} If the app module is not set (setup() was not called)\n *\n * @example\n * ```typescript\n * const app = await CommanderFactory.create(AppModule)\n * await app.init() // Must be called before run() or executeCommand()\n * ```\n */\n async init() {\n if (!this.appModule) {\n throw new Error(\n '[Navios Commander] App module is not set. Call setup() first.',\n )\n }\n await this.moduleLoader.loadModules(this.appModule)\n this.isInitialized = true\n }\n\n /**\n * Executes a command programmatically with the provided options.\n *\n * This method is useful for testing, automation, or programmatic workflows.\n * The options will be validated against the command's Zod schema if one is provided.\n *\n * @param commandPath - The command path (e.g., 'greet', 'user:create')\n * @param options - The command options object (will be validated if schema exists)\n * @throws {Error} If the application is not initialized\n * @throws {Error} If the command is not found\n * @throws {Error} If the command does not implement the execute method\n * @throws {ZodError} If options validation fails\n *\n * @example\n * ```typescript\n * await app.executeCommand('greet', {\n * name: 'World',\n * greeting: 'Hi'\n * })\n * ```\n */\n async executeCommand(commandPath: string, options: any = {}) {\n if (!this.isInitialized) {\n throw new Error(\n '[Navios Commander] Application is not initialized. Call init() first.',\n )\n }\n\n // Use pre-collected command metadata from module loading\n const commandWithMetadata = this.moduleLoader.getCommandByPath(commandPath)\n\n if (!commandWithMetadata) {\n throw new Error(`[Navios Commander] Command not found: ${commandPath}`)\n }\n\n const { class: commandClass, metadata } = commandWithMetadata\n\n // Validate options with zod schema if provided\n let validatedOptions = options\n if (metadata.optionsSchema) {\n validatedOptions = metadata.optionsSchema.parse(options)\n }\n\n // Create execution context and provide it to the container\n const executionContext = new CommanderExecutionContext(\n metadata,\n commandPath,\n validatedOptions,\n )\n\n // Generate a unique request ID for this command execution\n const requestId = `cmd-${Date.now()}-${Math.random().toString(36).substring(7)}`\n\n // Begin request context and add ExecutionContext\n const scopeContainer = this.container.beginRequest(requestId)\n scopeContainer.addInstance(CommandExecutionContext, executionContext)\n\n try {\n // Get command instance and execute\n const commandInstance = await scopeContainer.get<CommandHandler>(\n commandClass as unknown as InjectionToken<CommandHandler>,\n )\n\n if (!commandInstance.execute) {\n throw new Error(\n `[Navios Commander] Command ${commandPath} does not implement execute method`,\n )\n }\n\n await commandInstance.execute(validatedOptions)\n } finally {\n // Clean up request context\n await scopeContainer.endRequest()\n }\n }\n\n /**\n * Gets all registered commands with their paths and class references.\n *\n * @returns An array of objects containing the command path and class\n *\n * @example\n * ```typescript\n * const commands = app.getAllCommands()\n * commands.forEach(({ path }) => {\n * console.log(`Available: ${path}`)\n * })\n * ```\n */\n getAllCommands() {\n // Use pre-collected command metadata from module loading\n const commandsMap = this.moduleLoader.getAllCommandsWithMetadata()\n const commandsWithMetadata: Array<{\n path: string\n class: ClassTypeWithInstance<any>\n }> = []\n\n for (const [, { class: cmd, metadata }] of commandsMap) {\n commandsWithMetadata.push({\n path: metadata.path,\n class: cmd,\n })\n }\n\n return commandsWithMetadata\n }\n\n /**\n * Runs the CLI application by parsing command-line arguments and executing the appropriate command.\n *\n * This is the main entry point for CLI usage. It parses `argv`, validates options,\n * and executes the matching command. Supports help command (`help`, `--help`, `-h`)\n * which displays all available commands.\n *\n * @param argv - Command-line arguments array (defaults to `process.argv`)\n * @throws {Error} If the application is not initialized\n * @throws {Error} If no command is provided\n * @throws {Error} If the command is not found\n * @throws {ZodError} If options validation fails\n *\n * @example\n * ```typescript\n * // Parse and execute from process.argv\n * await app.run()\n *\n * // Or provide custom arguments\n * await app.run(['node', 'cli.js', 'greet', '--name', 'World'])\n * ```\n */\n async run(argv: string[] = process.argv) {\n if (!this.isInitialized) {\n throw new Error(\n '[Navios Commander] Application is not initialized. Call init() first.',\n )\n }\n\n try {\n // First, try to extract the command path to get its schema\n // We need to do a preliminary parse to find the command\n const preliminaryParse = this.cliParser.parse(argv)\n const commandWithMetadata = this.moduleLoader.getCommandByPath(\n preliminaryParse.command,\n )\n\n // Re-parse with schema if available\n const parsed = commandWithMetadata?.metadata.optionsSchema\n ? this.cliParser.parse(argv, commandWithMetadata.metadata.optionsSchema)\n : preliminaryParse\n\n // Handle special commands\n if (\n parsed.command === 'help' ||\n parsed.options.help ||\n parsed.options.h\n ) {\n const commands = this.getAllCommands()\n console.log(this.cliParser.formatCommandList(commands))\n return\n }\n\n // Execute the command\n await this.executeCommand(parsed.command, parsed.options)\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error: ${error.message}`)\n\n // Show available commands on error\n if (error.message.includes('Command not found')) {\n console.log(\n '\\n' + this.cliParser.formatCommandList(this.getAllCommands()),\n )\n }\n }\n throw error\n }\n }\n\n /**\n * @internal\n * Disposes of resources used by the application.\n */\n async dispose() {\n if (this.moduleLoader) {\n this.moduleLoader.dispose()\n }\n }\n\n /**\n * Closes the application and cleans up resources.\n *\n * This should be called when the application is no longer needed to free up resources.\n *\n * @example\n * ```typescript\n * await app.run(process.argv)\n * await app.close()\n * ```\n */\n async close() {\n await this.dispose()\n }\n}\n","import type { ClassTypeWithInstance, NaviosModule } from '@navios/core'\n\nimport { Container } from '@navios/core'\n\nimport type { CommanderApplicationOptions } from './commander.application.mjs'\n\nimport { CommanderApplication } from './commander.application.mjs'\n\n/**\n * Factory class for creating and configuring CLI applications.\n *\n * @example\n * ```typescript\n * import { CommanderFactory } from '@navios/commander'\n * import { AppModule } from './app.module'\n *\n * async function bootstrap() {\n * const app = await CommanderFactory.create(AppModule)\n * await app.init()\n * await app.run(process.argv)\n * await app.close()\n * }\n * ```\n */\nexport class CommanderFactory {\n /**\n * Creates a new CommanderApplication instance and configures it with the provided module.\n *\n * @param appModule - The root CLI module class that contains commands and/or imports other modules\n * @param options - Optional configuration options for the application\n * @returns A promise that resolves to a configured CommanderApplication instance\n *\n * @example\n * ```typescript\n * const app = await CommanderFactory.create(AppModule)\n * await app.init()\n * ```\n */\n static async create(\n appModule: ClassTypeWithInstance<NaviosModule>,\n options: CommanderApplicationOptions = {},\n ) {\n const container = new Container()\n const app = await container.get(CommanderApplication)\n await app.setup(appModule, options)\n return app\n }\n}\n","import type { ClassType } from '@navios/core'\nimport type { ZodObject } from 'zod'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/core'\n\nimport { getCommandMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for the `@Command` decorator.\n *\n * @public\n */\nexport interface CommandOptions {\n /**\n * The command path that users will invoke from the CLI.\n * Can be a single word (e.g., 'greet') or multi-word with colons (e.g., 'user:create', 'db:migrate').\n */\n path: string\n /**\n * Optional Zod schema for validating command options.\n * If provided, options will be validated and parsed according to this schema.\n */\n optionsSchema?: ZodObject\n}\n\n/**\n * Decorator that marks a class as a CLI command.\n *\n * The decorated class must implement the `CommandHandler` interface with an `execute` method.\n * The command will be automatically registered when its module is loaded.\n *\n * @param options - Configuration options for the command\n * @returns A class decorator function\n *\n * @example\n * ```typescript\n * import { Command, CommandHandler } from '@navios/commander'\n * import { z } from 'zod'\n *\n * const optionsSchema = z.object({\n * name: z.string(),\n * greeting: z.string().optional().default('Hello')\n * })\n *\n * @Command({\n * path: 'greet',\n * optionsSchema: optionsSchema\n * })\n * export class GreetCommand implements CommandHandler<z.infer<typeof optionsSchema>> {\n * async execute(options) {\n * console.log(`${options.greeting}, ${options.name}!`)\n * }\n * }\n * ```\n */\nexport function Command({ path, optionsSchema }: CommandOptions) {\n return function (target: ClassType, context: ClassDecoratorContext) {\n if (context.kind !== 'class') {\n throw new Error(\n '[Navios Commander] @Command decorator can only be used on classes.',\n )\n }\n const token = InjectionToken.create(target)\n if (context.metadata) {\n getCommandMetadata(target, context, path, optionsSchema)\n }\n return Injectable({\n token,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Injectable, InjectableScope, InjectionToken } from '@navios/core'\n\nimport { getCliModuleMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for the `@CliModule` decorator.\n *\n * @public\n */\nexport interface CliModuleOptions {\n /**\n * Array or Set of command classes to register in this module.\n * Commands must be decorated with `@Command`.\n */\n commands?: ClassType[] | Set<ClassType>\n /**\n * Array or Set of other CLI modules to import.\n * Imported modules' commands will be available in this module.\n */\n imports?: ClassType[] | Set<ClassType>\n}\n\n/**\n * Decorator that marks a class as a CLI module.\n *\n * Modules organize commands and can import other modules to compose larger CLI applications.\n * The module can optionally implement `NaviosModule` interface for lifecycle hooks.\n *\n * @param options - Configuration options for the module\n * @returns A class decorator function\n *\n * @example\n * ```typescript\n * import { CliModule } from '@navios/commander'\n * import { GreetCommand } from './greet.command'\n * import { UserModule } from './user.module'\n *\n * @CliModule({\n * commands: [GreetCommand],\n * imports: [UserModule]\n * })\n * export class AppModule {}\n * ```\n */\nexport function CliModule(\n { commands = [], imports = [] }: CliModuleOptions = {\n commands: [],\n imports: [],\n },\n) {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error(\n '[Navios Commander] @CliModule decorator can only be used on classes.',\n )\n }\n // Register the module in the service locator\n const token = InjectionToken.create(target)\n const moduleMetadata = getCliModuleMetadata(target, context)\n for (const command of commands) {\n moduleMetadata.commands.add(command)\n }\n for (const importedModule of imports) {\n moduleMetadata.imports.add(importedModule)\n }\n\n return Injectable({\n token,\n scope: InjectableScope.Singleton,\n })(target, context)\n }\n}\n","// Re-export DI types and values that users might need\nexport * from '@navios/core'\n\n// Export commander-specific exports\nexport * from './commander.application.mjs'\nexport * from './commander.factory.mjs'\nexport * from './decorators/index.mjs'\nexport * from './interfaces/index.mjs'\nexport * from './metadata/index.mjs'\nexport * from './services/index.mjs'\nexport * from './tokens/index.mjs'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAaA,sBAAsB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