@navios/core 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 +31 -0
- package/lib/{index-DW9EPAE6.d.mts → index-BDNl7j1G.d.cts} +515 -346
- package/lib/index-BDNl7j1G.d.cts.map +1 -0
- package/lib/{index-pHp-dIGt.d.cts → index-BoP0cWT6.d.mts} +515 -346
- package/lib/index-BoP0cWT6.d.mts.map +1 -0
- package/lib/index.cjs +12 -3
- package/lib/index.d.cts +2 -2
- package/lib/index.d.mts +2 -2
- package/lib/index.mjs +3 -3
- package/lib/legacy-compat/index.cjs +1 -1
- package/lib/legacy-compat/index.cjs.map +1 -1
- package/lib/legacy-compat/index.d.cts +1 -1
- package/lib/legacy-compat/index.d.mts +1 -1
- package/lib/legacy-compat/index.mjs +1 -1
- package/lib/legacy-compat/index.mjs.map +1 -1
- package/lib/{src-QnxR5b7c.cjs → src-B6eISODM.cjs} +465 -47
- package/lib/src-B6eISODM.cjs.map +1 -0
- package/lib/{src-DyvCDuKO.mjs → src-gBAChVRL.mjs} +445 -45
- package/lib/src-gBAChVRL.mjs.map +1 -0
- package/lib/testing/index.cjs +2 -2
- package/lib/testing/index.d.cts +1 -1
- package/lib/testing/index.d.mts +1 -1
- package/lib/testing/index.mjs +2 -2
- package/lib/{use-guards.decorator-B6q_N0sf.cjs → use-guards.decorator-COR-9mZY.cjs} +20 -94
- package/lib/use-guards.decorator-COR-9mZY.cjs.map +1 -0
- package/lib/{use-guards.decorator-kZ3lNK8v.mjs → use-guards.decorator-CUww54Nt.mjs} +14 -94
- package/lib/use-guards.decorator-CUww54Nt.mjs.map +1 -0
- package/package.json +4 -4
- package/src/__tests__/controller-resolver.spec.mts +223 -0
- package/src/__tests__/controller.spec.mts +1 -1
- package/src/decorators/controller.decorator.mts +11 -6
- package/src/decorators/endpoint.decorator.mts +60 -12
- package/src/decorators/multipart.decorator.mts +67 -24
- package/src/decorators/stream.decorator.mts +65 -24
- package/src/interfaces/abstract-http-handler-adapter.interface.mts +31 -1
- package/src/legacy-compat/decorators/endpoint.decorator.mts +1 -1
- package/src/legacy-compat/decorators/multipart.decorator.mts +1 -1
- package/src/legacy-compat/decorators/stream.decorator.mts +1 -1
- package/src/logger/logger.service.mts +0 -2
- package/src/navios.application.mts +14 -0
- package/src/navios.factory.mts +19 -0
- package/src/services/guard-runner.service.mts +46 -9
- package/src/services/index.mts +1 -0
- package/src/services/instance-resolver.service.mts +186 -0
- package/src/stores/request-id.store.mts +45 -3
- package/src/tokens/index.mts +1 -0
- package/src/tokens/navios-options.token.mts +6 -0
- package/lib/index-DW9EPAE6.d.mts.map +0 -1
- package/lib/index-pHp-dIGt.d.cts.map +0 -1
- package/lib/src-DyvCDuKO.mjs.map +0 -1
- package/lib/src-QnxR5b7c.cjs.map +0 -1
- package/lib/use-guards.decorator-B6q_N0sf.cjs.map +0 -1
- package/lib/use-guards.decorator-kZ3lNK8v.mjs.map +0 -1
package/lib/src-QnxR5b7c.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-QnxR5b7c.cjs","names":["env","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","console","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","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","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"],"sources":["../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"],"sourcesContent":["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 console.log('log', message, optionalParams)\n console.log('localInstance', this.localInstance)\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 { 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/**\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'\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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAgB,OACd,KACA,cACQ;CACR,MAAM,SAASA,iBAAI,QAAQ,QAAQ,IAAI;AAEvC,QAAO,SAAS,SAAS,QAAkB,GAAG,GAAG;;AAGnD,SAAgB,UAId,KACA,cACoD;AACpD,QAAQA,iBAAI,QACV,QAAQ,IAAI,QACZ,gBACA;;;;;ACnBJ,MAAM,uBAAuB,CAAC,QAAQ,IAAI;AAC1C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AA,IAAWtB,MAAMsB,OAAAA,EAAS;AAI1CC,IAHwB,MAAMd,UAAUO,IACtCf,aAAAA,GAEcgB,MAAM,EACpBO,WAAWF,QACb,CAAA;AACA;;AAEF,MAAI,WAAwB,QAAQ,CAACtB,MAAMsB,OAAAA,CACzCb,WACGgB,mBAAiB,CACjBC,YAAU,CACVC,mBACC1B,aAAa2B,UAAQ,EACrBN,QACAvB,0BAAe8B,OACf/B,2BAAgBgC,UAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-guards.decorator-B6q_N0sf.cjs","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"],"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"],"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"],"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,OAAOO,KAAI;AAE5C,OAAIN,iBACF,QAAOA;QACF;IACL,MAAMO,cAAuC;KAC3CF,aAAaN,OAAOO;KACpBE,KAAK;KACLC,mBAAmB;KACnBC,cAAc;KACdC,SAAS,EAAC;KACVC,YAAY;KAEZC,QAAQ;KACRC,wBAAQ,IAAIlB,KAAAA;KAIZmB,kCAAkB,IAAIC,KAAAA;KACxB;AACArB,aAASsB,IAAIV,YAAAA;AACb,WAAOA;;;;AAIb,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MAAMH,OAAOG;;AAEhC,SAAOP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GC/EX,SAAgBe,UACd,GAAGC,QAGA;AAEH,QAAO,SACLC,QACAC,SAA4D;AAE5D,MAAIA,QAAQC,SAAS,SAAS;GAC5B,MAAMC,qBAAqBP,sBACzBI,QACAC,QAAAA;AAEF,QAAK,MAAMG,SAASL,OAAOM,SAAO,CAChCF,oBAAmBJ,OAAOO,IAAIF,MAAAA;aAEvBH,QAAQC,SAAS,UAAU;GACpC,MAAMK,mBAAmBV,oBAAoBG,QAAQC,QAAAA;AACrD,QAAK,MAAMG,SAASL,OAAOM,SAAO,CAChCE,kBAAiBR,OAAOO,IAAIF,MAAAA;QAG9B,OAAM,IAAII,MACR,wEAAA;AAGJ,SAAOR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-guards.decorator-kZ3lNK8v.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"],"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"],"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"],"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,OAAOO,KAAI;AAE5C,OAAIN,iBACF,QAAOA;QACF;IACL,MAAMO,cAAuC;KAC3CF,aAAaN,OAAOO;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