{"version":3,"file":"index.mjs","names":["AbstractHandlerAdapterService","AbstractFastifyHandlerAdapterService","createArgumentGetters","handlerMetadata","config","getters","querySchema","push","target","request","params","query","requestSchema","data","body","hasUrlParams","urlParams","hasSchema","options","validateResponses","errorSchema","provideSchema","schema","querystring","response","AbstractFastifyHandlerAdapterService","Injectable","InjectionToken","FastifyStreamAdapterToken","create","Symbol","for","token","FastifyStreamAdapterService","createStaticHandler","boundMethod","formatArguments","context","hasArguments","isStatic","handler","request","reply","argument","emptyArgs","Object","freeze","_request","createDynamicHandler","resolution","methodName","scoped","controllerInstance","resolve","FastifyStreamAdapterService","Injectable","InjectionToken","FastifyEndpointAdapterToken","create","Symbol","for","token","FastifyEndpointAdapterService","hasSchema","handlerMetadata","config","options","validateResponses","responseSchema","provideSchema","schema","response","errorSchema","createStaticHandler","boundMethod","formatArguments","context","statusCode","headers","hasArguments","isStatic","handler","request","reply","argument","result","status","send","emptyArgs","Object","freeze","_request","createDynamicHandler","resolution","methodName","scoped","controllerInstance","resolve","FastifyEndpointAdapterService","Injectable","InjectionToken","ZodArray","ZodObject","ZodOptional","FastifyMultipartAdapterToken","create","Symbol","for","token","FastifyMultipartAdapterService","createArgumentGetters","handlerMetadata","config","getters","querySchema","push","target","request","params","query","hasUrlParams","urlParams","requestSchema","shape","_zod","def","structure","analyzeSchema","req","part","parts","populateRequest","data","parse","provideSchema","schema","responseSchema","querystring","options","validateResponses","response","errorSchema","isArray","isObject","fieldname","value","type","File","toBuffer","filename","mimetype","JSON","Object","keys","reduce","key","isOptional","unwrap","element","FastifyExecutionContext","module","controller","handler","request","reply","getModule","getController","getHandler","getRequest","Error","getReply","InjectionToken","FastifyServerToken","create","InjectionToken","FastifyRequestToken","create","InjectionToken","FastifyReplyToken","create","InjectionToken","FastifyApplicationServiceToken","create","Container","ErrorResponseProducerService","ExecutionContext","extractControllerMetadata","FrameworkError","GuardRunnerService","HttpException","inject","Injectable","InstanceResolverService","Logger","runWithRequestId","ZodError","FastifyExecutionContext","FastifyReplyToken","FastifyRequestToken","FastifyControllerAdapterService","guardRunner","container","instanceResolver","errorProducer","logger","context","name","setupController","controller","instance","moduleMetadata","controllerMetadata","endpoint","endpoints","classMethod","url","httpMethod","adapterToken","Error","adapter","get","guards","makeContext","guardResolution","resolveMany","Array","from","reverse","hasSchema","handlerResult","provideHandler","preHandler","handler","wrapHandler","withTypeProvider","route","method","replaceAll","schema","provideSchema","debug","createRequestContainer","request","reply","beginRequest","id","scopedContainer","addInstance","createExecutionContext","makeStaticHandler","sent","error","handleError","makeDynamicHandler","makeStaticGuardsPreHandler","guardInstances","setupContainer","runGuardsStatic","makeDynamicGuardsPreHandler","runGuards","hasGuards","classTypes","length","guardsAreStatic","cached","handlerIsStatic","isStatic","instances","Set","errorResponse","status","statusCode","send","response","respond","ValidationError","err","message","handleUnknown","type","payload","Injectable","safeParse","FastifyValidatorCompilerService","errorCompiler","schema","data","result","error","value","Container","inject","Injectable","Logger","PinoWrapper","container","logger","fatal","message","optionalParams","undefined","error","warn","info","debug","trace","verbose","silent","child","options","keys","Object","newContext","length","JSON","stringify","loggerPromise","get","context","newPinoWrapper","create","prototype","then","level","logLevels","Array","isArray","find","Container","ErrorResponseProducerService","FrameworkError","HttpException","inject","Injectable","Logger","cors","multipart","fastify","serializerCompiler","ZodError","$ZodError","FastifyApplicationServiceToken","FastifyServerToken","FastifyControllerAdapterService","FastifyValidatorCompilerService","PinoWrapper","token","FastifyApplicationService","logger","context","name","container","errorProducer","validatorCompiler","server","controllerAdapter","globalPrefix","corsOptions","multipartOptions","configureOptions","setupAdapter","options","mergedOptions","fastifyOptions","serverOptions","loggerInstance","get","initServer","configureFastifyInstance","registerFastifyInstance","configurePlugins","ready","setGlobalPrefix","prefix","getGlobalPrefix","getServer","Error","onModulesInit","modules","promises","_moduleName","moduleMetadata","controllers","size","push","register","instance","_opts","controller","setupController","Promise","all","setErrorHandler","error","request","reply","status","statusCode","send","response","errorResponse","respond","ValidationError","type","payload","message","url","InternalServerError","setNotFoundHandler","req","warn","method","NotFound","decorateRequest","undefined","addHook","scopedContainer","endRequest","catch","err","setValidatorCompiler","errorCompiler","setSerializerCompiler","configureMultipart","addInstance","enableCors","enableMultipart","listen","res","debug","configure","dispose","close","AdapterToken","EndpointAdapterToken","HttpAdapterToken","MultipartAdapterToken","Reply","Request","StreamAdapterToken","FastifyEndpointAdapterService","FastifyMultipartAdapterService","FastifyStreamAdapterService","FastifyApplicationService","FastifyReplyToken","FastifyRequestToken","defineFastifyEnvironment","tokens","Map"],"sources":["../src/adapters/abstract-fastify-handler-adapter.service.mts","../src/adapters/stream-adapter.service.mts","../src/adapters/endpoint-adapter.service.mts","../src/adapters/multipart-adapter.service.mts","../src/interfaces/fastify-execution-context.interface.mts","../src/tokens/server.token.mts","../src/tokens/request.token.mts","../src/tokens/reply.token.mts","../src/tokens/fastify-application.token.mts","../src/services/controller-adapter.service.mts","../src/services/fastify-validator-compiler.service.mts","../src/services/pino-wrapper.mts","../src/services/application.service.mts","../src/define-environment.mts"],"sourcesContent":["import type { BaseEndpointOptions } from '@navios/builder'\nimport type { HandlerMetadata } from '@navios/core'\nimport type { FastifyReply, FastifyRequest } from 'fastify'\n\nimport {\n  AbstractHandlerAdapterService,\n  type ArgumentGetter,\n} from '@navios/core'\n\n/**\n * Abstract base class for Fastify handler adapters.\n *\n * Provides shared argument parsing logic for Fastify:\n * - Query parameters via request.query\n * - Request body via request.body\n * - URL parameters via request.params\n *\n * Concrete adapters (Endpoint, Stream) implement response handling\n * via createStaticHandler and createDynamicHandler.\n *\n * @typeParam TConfig - Endpoint configuration type\n */\nexport abstract class AbstractFastifyHandlerAdapterService<\n  TConfig extends BaseEndpointOptions = BaseEndpointOptions,\n> extends AbstractHandlerAdapterService<FastifyRequest, FastifyReply, TConfig> {\n  /**\n   * Creates argument getters for Fastify request parsing.\n   *\n   * Handles:\n   * - Query params: Extracts from request.query (pre-validated by Fastify)\n   * - Request body: Extracts from request.body (pre-validated by Fastify)\n   * - URL params: Extracts route parameters from request.params\n   */\n  protected override createArgumentGetters(\n    handlerMetadata: HandlerMetadata<TConfig>,\n  ): ArgumentGetter<FastifyRequest>[] {\n    const config = handlerMetadata.config\n    const getters: ArgumentGetter<FastifyRequest>[] = []\n\n    if (config.querySchema) {\n      getters.push((target, request) => {\n        target.params = request.query\n      })\n    }\n\n    if (config.requestSchema) {\n      getters.push((target, request) => {\n        target.data = request.body\n      })\n    }\n\n    if (this.hasUrlParams(config)) {\n      getters.push((target, request) => {\n        target.urlParams = request.params\n      })\n    }\n\n    return getters\n  }\n\n  /**\n   * Checks if the handler has any validation schemas defined.\n   *\n   * @param handlerMetadata - The handler metadata containing configuration.\n   * @returns `true` if the handler has request, query, or error schemas.\n   */\n  override hasSchema(handlerMetadata: HandlerMetadata<TConfig>): boolean {\n    const config = handlerMetadata.config\n    return (\n      !!config.requestSchema ||\n      !!config.querySchema ||\n      (!!this.options.validateResponses && !!config.errorSchema)\n    )\n  }\n\n  /**\n   * Provides Fastify schema information for the handler.\n   *\n   * Creates a Fastify route schema object that includes request body and\n   * query string schemas. This enables Fastify's built-in validation.\n   *\n   * @param handlerMetadata - The handler metadata containing configuration and schemas.\n   * @returns A Fastify route schema object.\n   */\n  override provideSchema(\n    handlerMetadata: HandlerMetadata<TConfig>,\n  ): Record<string, any> {\n    const schema: Record<string, any> = {}\n    const { querySchema, requestSchema, errorSchema } = handlerMetadata.config\n\n    if (querySchema) {\n      schema.querystring = querySchema\n    }\n    if (requestSchema) {\n      schema.body = requestSchema\n    }\n    if (this.options.validateResponses && errorSchema) {\n      schema.response = {\n        ...errorSchema,\n      }\n    }\n\n    return schema\n  }\n}\n","import type { BaseEndpointOptions } from '@navios/builder'\nimport type {\n  AbstractDynamicHandler,\n  AbstractStaticHandler,\n  FormatArgumentsFn,\n  HandlerContext,\n  InstanceResolution,\n} from '@navios/core'\nimport type { FastifyReply, FastifyRequest } from 'fastify'\n\nimport { Injectable, InjectionToken } from '@navios/core'\n\nimport { AbstractFastifyHandlerAdapterService } from './abstract-fastify-handler-adapter.service.mjs'\n\n/**\n * Injection token for the Fastify stream adapter service.\n *\n * This token is used to inject the `FastifyStreamAdapterService` instance\n * into the dependency injection container.\n */\nexport const FastifyStreamAdapterToken =\n  InjectionToken.create<FastifyStreamAdapterService>(\n    Symbol.for('FastifyStreamAdapterService'),\n  )\n\n/**\n * Adapter service for handling streaming requests and responses in Fastify.\n *\n * This service extends `AbstractFastifyHandlerAdapterService` and provides\n * handling for stream-based endpoints. Handlers receive the Fastify reply\n * object for direct control over the response stream.\n *\n * @extends {AbstractFastifyHandlerAdapterService<BaseEndpointOptions>}\n *\n * @example\n * ```ts\n * // Used automatically when defining endpoints with @Stream()\n * @Controller()\n * class StreamController {\n *   @Stream(streamEvents)\n *   async streamData(data: StreamDto, reply: FastifyReply) {\n *     reply.type('text/event-stream')\n *     // Use reply object to stream data\n *     reply.send(stream)\n *   }\n * }\n * ```\n */\n@Injectable({\n  token: FastifyStreamAdapterToken,\n})\nexport class FastifyStreamAdapterService extends AbstractFastifyHandlerAdapterService<BaseEndpointOptions> {\n  /**\n   * Creates a static handler for singleton controllers.\n   *\n   * Passes the Fastify reply object as the second argument to the controller method\n   * for direct stream control.\n   *\n   * @param boundMethod - Pre-bound controller method\n   * @param formatArguments - Function to format request arguments\n   * @param context - Handler context with metadata\n   * @returns Static handler result\n   */\n  protected override createStaticHandler(\n    boundMethod: (...args: any[]) => Promise<any>,\n    formatArguments: FormatArgumentsFn<FastifyRequest>,\n    context: HandlerContext<BaseEndpointOptions>,\n  ): AbstractStaticHandler<FastifyRequest, FastifyReply> {\n    if (context.hasArguments) {\n      return {\n        isStatic: true,\n        handler: async (request: FastifyRequest, reply: FastifyReply) => {\n          const argument = await formatArguments(request)\n          await boundMethod(argument, reply)\n        },\n      }\n    }\n\n    const emptyArgs = Object.freeze({})\n    return {\n      isStatic: true,\n      handler: async (_request: FastifyRequest, reply: FastifyReply) => {\n        await boundMethod(emptyArgs, reply)\n      },\n    }\n  }\n\n  /**\n   * Creates a dynamic handler for request-scoped controllers.\n   *\n   * Passes the Fastify reply object as the second argument to the controller method\n   * for direct stream control.\n   *\n   * @param resolution - Instance resolution with resolve function\n   * @param formatArguments - Function to format request arguments\n   * @param context - Handler context with metadata\n   * @returns Dynamic handler result\n   */\n  protected override createDynamicHandler(\n    resolution: InstanceResolution,\n    formatArguments: FormatArgumentsFn<FastifyRequest>,\n    context: HandlerContext<BaseEndpointOptions>,\n  ): AbstractDynamicHandler<FastifyRequest, FastifyReply> {\n    const { methodName, hasArguments } = context\n\n    if (hasArguments) {\n      return {\n        isStatic: false,\n        handler: async (\n          scoped,\n          request: FastifyRequest,\n          reply: FastifyReply,\n        ) => {\n          const controllerInstance = (await resolution.resolve(scoped)) as any\n          const argument = await formatArguments(request)\n          await controllerInstance[methodName](argument, reply)\n        },\n      }\n    }\n\n    const emptyArgs = Object.freeze({})\n    return {\n      isStatic: false,\n      handler: async (\n        scoped,\n        _request: FastifyRequest,\n        reply: FastifyReply,\n      ) => {\n        const controllerInstance = (await resolution.resolve(scoped)) as any\n        await controllerInstance[methodName](emptyArgs, reply)\n      },\n    }\n  }\n}\n","import type { EndpointOptions } from '@navios/builder'\nimport type {\n  AbstractDynamicHandler,\n  AbstractStaticHandler,\n  FormatArgumentsFn,\n  HandlerContext,\n  HandlerMetadata,\n  InstanceResolution,\n} from '@navios/core'\nimport type { FastifyReply, FastifyRequest } from 'fastify'\n\nimport { Injectable, InjectionToken } from '@navios/core'\n\nimport { FastifyStreamAdapterService } from './stream-adapter.service.mjs'\n\n/**\n * Injection token for the Fastify endpoint adapter service.\n *\n * This token is used to inject the `FastifyEndpointAdapterService` instance\n * into the dependency injection container.\n */\nexport const FastifyEndpointAdapterToken =\n  InjectionToken.create<FastifyEndpointAdapterService>(\n    Symbol.for('FastifyEndpointAdapterService'),\n  )\n\n/**\n * Adapter service for handling standard REST endpoint requests in Fastify.\n *\n * This service extends `FastifyStreamAdapterService` and provides specialized\n * handling for REST endpoints with request/response schema validation.\n * It automatically parses request bodies, query parameters, and URL parameters,\n * validates them against Zod schemas, and formats responses according to\n * response schemas using Fastify's schema system.\n *\n * @extends {FastifyStreamAdapterService}\n *\n * @example\n * ```ts\n * // Used automatically when defining endpoints with @Endpoint()\n * @Controller()\n * class UserController {\n *   @Endpoint({\n *     method: 'POST',\n *     url: '/users',\n *     requestSchema: createUserSchema,\n *     responseSchema: userSchema,\n *   })\n *   async createUser(data: CreateUserDto) {\n *     // data is validated against createUserSchema\n *     return { id: 1, ...data } // Response validated against userSchema\n *   }\n * }\n * ```\n */\n@Injectable({\n  token: FastifyEndpointAdapterToken,\n})\nexport class FastifyEndpointAdapterService extends FastifyStreamAdapterService {\n  /**\n   * Checks if the handler has any validation schemas defined.\n   *\n   * @param handlerMetadata - The handler metadata containing configuration.\n   * @returns `true` if the handler has request, query, or response schemas.\n   */\n  override hasSchema(\n    handlerMetadata: HandlerMetadata<EndpointOptions>,\n  ): boolean {\n    const config = handlerMetadata.config\n    return (\n      super.hasSchema(handlerMetadata) ||\n      (!!this.options.validateResponses && !!config.responseSchema)\n    )\n  }\n\n  /**\n   * Provides Fastify schema information for the handler.\n   *\n   * Creates a Fastify route schema object that includes request body, query string,\n   * and response schemas. This enables Fastify's built-in validation and serialization.\n   *\n   * @param handlerMetadata - The handler metadata containing configuration and schemas.\n   * @returns A Fastify route schema object.\n   */\n  override provideSchema(\n    handlerMetadata: HandlerMetadata<EndpointOptions>,\n  ): Record<string, any> {\n    const config = handlerMetadata.config\n    const schema = super.provideSchema(handlerMetadata)\n    if (this.options.validateResponses && config.responseSchema) {\n      schema.response = {\n        ...config.errorSchema,\n        200: config.responseSchema,\n      }\n    }\n\n    return schema\n  }\n\n  /**\n   * Creates a static handler for singleton controllers.\n   *\n   * Invokes the controller method and sends the response with proper status and headers.\n   *\n   * @param boundMethod - Pre-bound controller method\n   * @param formatArguments - Function to format request arguments\n   * @param context - Handler context with metadata\n   * @returns Static handler result\n   */\n  protected override createStaticHandler(\n    boundMethod: (...args: any[]) => Promise<any>,\n    formatArguments: FormatArgumentsFn<FastifyRequest>,\n    context: HandlerContext<EndpointOptions>,\n  ): AbstractStaticHandler<FastifyRequest, FastifyReply> {\n    const { statusCode, headers, hasArguments } = context\n\n    if (hasArguments) {\n      return {\n        isStatic: true,\n        handler: async (request: FastifyRequest, reply: FastifyReply) => {\n          const argument = await formatArguments(request)\n          const result = await boundMethod(argument)\n          reply.status(statusCode).headers(headers).send(result)\n        },\n      }\n    }\n\n    const emptyArgs = Object.freeze({})\n    return {\n      isStatic: true,\n      handler: async (_request: FastifyRequest, reply: FastifyReply) => {\n        const result = await boundMethod(emptyArgs)\n        reply.status(statusCode).headers(headers).send(result)\n      },\n    }\n  }\n\n  /**\n   * Creates a dynamic handler for request-scoped controllers.\n   *\n   * Resolves the controller per-request and sends the response with proper status and headers.\n   *\n   * @param resolution - Instance resolution with resolve function\n   * @param formatArguments - Function to format request arguments\n   * @param context - Handler context with metadata\n   * @returns Dynamic handler result\n   */\n  protected override createDynamicHandler(\n    resolution: InstanceResolution,\n    formatArguments: FormatArgumentsFn<FastifyRequest>,\n    context: HandlerContext<EndpointOptions>,\n  ): AbstractDynamicHandler<FastifyRequest, FastifyReply> {\n    const { methodName, statusCode, headers, hasArguments } = context\n\n    if (hasArguments) {\n      return {\n        isStatic: false,\n        handler: async (\n          scoped,\n          request: FastifyRequest,\n          reply: FastifyReply,\n        ) => {\n          const controllerInstance = (await resolution.resolve(scoped)) as any\n          const argument = await formatArguments(request)\n          const result = await controllerInstance[methodName](argument)\n          reply.status(statusCode).headers(headers).send(result)\n        },\n      }\n    }\n\n    const emptyArgs = Object.freeze({})\n    return {\n      isStatic: false,\n      handler: async (\n        scoped,\n        _request: FastifyRequest,\n        reply: FastifyReply,\n      ) => {\n        const controllerInstance = (await resolution.resolve(scoped)) as any\n        const result = await controllerInstance[methodName](emptyArgs)\n        reply.status(statusCode).headers(headers).send(result)\n      },\n    }\n  }\n}\n","import type { MultipartFile, MultipartValue } from '@fastify/multipart'\nimport type { EndpointOptions } from '@navios/builder'\nimport type { ArgumentGetter, HandlerMetadata } from '@navios/core'\nimport type { FastifyRequest } from 'fastify'\nimport type { ZodRawShape } from 'zod/v4'\n\nimport { Injectable, InjectionToken } from '@navios/core'\n\nimport { ZodArray, ZodObject, ZodOptional } from 'zod/v4'\n\nimport { FastifyEndpointAdapterService } from './endpoint-adapter.service.mjs'\n\n/**\n * Injection token for the Fastify multipart adapter service.\n *\n * This token is used to inject the `FastifyMultipartAdapterService` instance\n * into the dependency injection container.\n */\nexport const FastifyMultipartAdapterToken =\n  InjectionToken.create<FastifyMultipartAdapterService>(\n    Symbol.for('FastifyMultipartAdapterService'),\n  )\n\n/**\n * Adapter service for handling multipart/form-data requests in Fastify.\n *\n * This service extends `FastifyEndpointAdapterService` and provides specialized\n * handling for file uploads and multipart form data. It automatically parses\n * multipart streams, handles file uploads, converts files to File objects,\n * and validates the data against Zod schemas.\n *\n * @extends {FastifyEndpointAdapterService}\n *\n * @example\n * ```ts\n * // Used automatically when defining endpoints with @Multipart()\n * @Controller()\n * class UploadController {\n *   @Multipart({\n *     method: 'POST',\n *     url: '/upload',\n *     requestSchema: uploadSchema,\n *   })\n *   async uploadFile(data: UploadDto) {\n *     // data contains parsed form fields and File objects\n *     return { success: true }\n *   }\n * }\n * ```\n */\n@Injectable({\n  token: FastifyMultipartAdapterToken,\n})\nexport class FastifyMultipartAdapterService extends FastifyEndpointAdapterService {\n  /**\n   * Creates argument getters for parsing multipart form data.\n   *\n   * This method creates an array of functions that extract and validate\n   * data from multipart requests, including:\n   * - Query parameters\n   * - URL parameters\n   * - Form fields and file uploads from multipart streams\n   *\n   * Files are converted to File objects, and form fields are parsed and\n   * validated against the request schema. Supports arrays and nested objects.\n   *\n   * @param handlerMetadata - The handler metadata with schemas and configuration.\n   * @returns An array of getter functions that populate request arguments.\n   */\n  protected override createArgumentGetters(\n    handlerMetadata: HandlerMetadata<EndpointOptions>,\n  ): ArgumentGetter<FastifyRequest>[] {\n    const config = handlerMetadata.config\n    const getters: ArgumentGetter<FastifyRequest>[] = []\n\n    if (config.querySchema) {\n      getters.push((target, request) => {\n        target.params = request.query\n      })\n    }\n\n    if (this.hasUrlParams(config)) {\n      getters.push((target, request) => {\n        target.urlParams = request.params\n      })\n    }\n\n    const requestSchema = config.requestSchema as unknown as ZodObject\n    const shape = requestSchema._zod.def.shape\n    const structure = this.analyzeSchema(shape)\n\n    getters.push(async (target, request) => {\n      const req: Record<string, any> = {}\n      for await (const part of request.parts()) {\n        await this.populateRequest(structure, part, req)\n      }\n      target.data = requestSchema.parse(req)\n    })\n\n    return getters\n  }\n\n  /**\n   * Provides Fastify schema information for multipart handlers.\n   *\n   * Creates a Fastify route schema object that includes query string and\n   * response schemas. Note that multipart body schemas are handled separately\n   * during request parsing.\n   *\n   * @param handlerMetadata - The handler metadata containing configuration and schemas.\n   * @returns A Fastify route schema object.\n   */\n  override provideSchema(\n    handlerMetadata: HandlerMetadata<EndpointOptions>,\n  ): Record<string, any> {\n    const schema: Record<string, any> = {}\n    const { querySchema, responseSchema } = handlerMetadata.config\n\n    if (querySchema) {\n      schema.querystring = querySchema\n    }\n    if (this.options.validateResponses && responseSchema) {\n      schema.response = {\n        ...handlerMetadata.config.errorSchema,\n        200: responseSchema,\n      }\n    }\n\n    return schema\n  }\n\n  /**\n   * Populates the request object with multipart data.\n   *\n   * Handles file uploads, form fields, arrays, and nested objects based on\n   * the schema structure.\n   *\n   * @param structure - Schema structure analysis results.\n   * @param part - Multipart part (file or value).\n   * @param req - Request object to populate.\n   * @private\n   */\n  private async populateRequest(\n    structure: {\n      [p: string]: { isArray: boolean; isOptional: boolean; isObject: boolean }\n    },\n    part: MultipartFile | MultipartValue<unknown>,\n    req: Record<string, any>,\n  ) {\n    const { isArray, isObject } = structure[part.fieldname] ?? {}\n    if (isArray && !req[part.fieldname]) {\n      req[part.fieldname] = []\n    }\n    let value\n    if (part.type === 'file') {\n      value = new File(\n        [(await part.toBuffer()) as unknown as ArrayBuffer],\n        part.filename,\n        {\n          type: part.mimetype,\n        },\n      )\n    } else {\n      value = part.value\n      if (isObject && typeof value === 'string') {\n        try {\n          value = JSON.parse(value)\n        } catch {\n          value = null\n        }\n      }\n    }\n\n    if (isArray) {\n      req[part.fieldname].push(value)\n    } else {\n      req[part.fieldname] = value\n    }\n  }\n\n  /**\n   * Analyzes the Zod schema shape to determine field types.\n   *\n   * Determines which fields are arrays, optional, or objects to properly\n   * handle multipart parsing.\n   *\n   * @param shape - The Zod schema shape definition.\n   * @returns An object mapping field names to their type information.\n   * @private\n   */\n  private analyzeSchema(shape: ZodRawShape) {\n    return Object.keys(shape).reduce(\n      (target, key) => {\n        let schema = shape[key]\n        const isOptional = schema instanceof ZodOptional\n        if (isOptional) {\n          schema = (schema as ZodOptional<any>).unwrap()\n        }\n        const isArray = schema instanceof ZodArray\n        if (isArray) {\n          schema = (schema as ZodArray<any>).element\n        }\n        const isObject = schema instanceof ZodObject\n        return {\n          ...target,\n          [key]: {\n            isArray,\n            isOptional,\n            isObject,\n          },\n        }\n      },\n      {} as Record<\n        string,\n        { isArray: boolean; isOptional: boolean; isObject: boolean }\n      >,\n    )\n  }\n}\n","import type {\n  AbstractExecutionContext,\n  ControllerMetadata,\n  HandlerMetadata,\n  ModuleMetadata,\n} from '@navios/core'\nimport type { FastifyReply, FastifyRequest } from 'fastify'\n\n/**\n * Execution context for Fastify adapter requests.\n *\n * This class provides access to metadata about the current request's\n * module, controller, handler, request, and reply objects. It's used by guards,\n * interceptors, and other request-scoped services to access context\n * information and interact with Fastify's request/reply objects.\n *\n * @implements {AbstractExecutionContext}\n *\n * @example\n * ```ts\n * @Injectable()\n * class AuthGuard implements CanActivate {\n *   canActivate(context: FastifyExecutionContext): boolean {\n *     const request = context.getRequest()\n *     const reply = context.getReply()\n *     const handler = context.getHandler()\n *     // Check authentication based on handler metadata\n *     return true\n *   }\n * }\n * ```\n */\nexport class FastifyExecutionContext implements AbstractExecutionContext {\n  constructor(\n    private readonly module: ModuleMetadata,\n    private readonly controller: ControllerMetadata,\n    private readonly handler: HandlerMetadata,\n    private readonly request: FastifyRequest,\n    private readonly reply: FastifyReply,\n  ) {}\n\n  /**\n   * Gets the module metadata for the current request.\n   *\n   * @returns The module metadata containing module configuration and dependencies.\n   */\n  getModule(): ModuleMetadata {\n    return this.module\n  }\n\n  /**\n   * Gets the controller metadata for the current request.\n   *\n   * @returns The controller metadata containing controller configuration.\n   */\n  getController(): ControllerMetadata {\n    return this.controller\n  }\n\n  /**\n   * Gets the handler metadata for the current request.\n   *\n   * @returns The handler metadata containing endpoint configuration, schemas, and method information.\n   */\n  getHandler(): HandlerMetadata {\n    return this.handler\n  }\n\n  /**\n   * Gets the current Fastify request object.\n   *\n   * @returns The Fastify request object for the current request.\n   * @throws {Error} If the request is not set.\n   */\n  getRequest(): FastifyRequest {\n    if (!this.request) {\n      throw new Error(\n        '[Navios] Request is not set. Make sure to set it before using it.',\n      )\n    }\n    return this.request\n  }\n\n  /**\n   * Gets the current Fastify reply object.\n   *\n   * The reply object provides methods for sending responses, setting headers,\n   * and controlling the response stream.\n   *\n   * @returns The Fastify reply object for the current request.\n   * @throws {Error} If the reply is not set.\n   */\n  getReply(): FastifyReply {\n    if (!this.reply) {\n      throw new Error(\n        '[Navios] Reply is not set. Make sure to set it before using it.',\n      )\n    }\n    return this.reply\n  }\n}\n","import type { FastifyInstance } from 'fastify'\n\nimport { InjectionToken } from '@navios/core'\n\n/**\n * Injection token for the Fastify server instance.\n *\n * This token provides access to the underlying Fastify server instance,\n * allowing direct interaction with Fastify's API for advanced use cases\n * such as registering custom plugins, hooks, decorators, or accessing\n * server-level functionality.\n *\n * @example\n * ```ts\n * @Injectable()\n * class PluginService {\n *   private server = inject(FastifyServerToken)\n *\n *   async registerStaticFiles() {\n *     await this.server.register(require('@fastify/static'), {\n *       root: path.join(__dirname, 'public'),\n *       prefix: '/public/',\n *     })\n *   }\n * }\n * ```\n */\nexport const FastifyServerToken =\n  InjectionToken.create<FastifyInstance>('FastifyServerToken')\n","import type { FastifyRequest } from 'fastify'\n\nimport { InjectionToken } from '@navios/core'\n\n/**\n * Injection token for the current Fastify request object.\n *\n * This token provides access to the current HTTP request within request-scoped\n * services. The request is automatically injected into the request-scoped container\n * for each incoming request.\n *\n * @example\n * ```ts\n * @Injectable()\n * class RequestService {\n *   private request = inject(FastifyRequestToken)\n *\n *   getUrl() {\n *     return this.request.url\n *   }\n *\n *   getMethod() {\n *     return this.request.method\n *   }\n *\n *   getHeaders() {\n *     return this.request.headers\n *   }\n * }\n * ```\n */\nexport const FastifyRequestToken = InjectionToken.create<FastifyRequest>(\n  'FastifyRequestToken',\n)\n","import type { FastifyReply } from 'fastify'\n\nimport { InjectionToken } from '@navios/core'\n\n/**\n * Injection token for the current Fastify reply object.\n *\n * This token provides access to the current HTTP response object within request-scoped\n * services. The reply is automatically injected into the request-scoped container\n * for each incoming request, allowing direct control over the response.\n *\n * @example\n * ```ts\n * @Injectable()\n * class ResponseService {\n *   private reply = inject(FastifyReplyToken)\n *\n *   setHeader(key: string, value: string) {\n *     this.reply.header(key, value)\n *   }\n *\n *   send(data: any) {\n *     this.reply.send(data)\n *   }\n * }\n * ```\n */\nexport const FastifyReplyToken =\n  InjectionToken.create<FastifyReply>('FastifyReplyToken')\n","import { InjectionToken } from '@navios/core'\n\nimport type { FastifyApplicationServiceInterface } from '../interfaces/application.interface.mjs'\n\n/**\n * Injection token for the Fastify application service.\n *\n * This token is used to inject the `FastifyApplicationService` instance\n * into the dependency injection container. It provides access to the\n * HTTP adapter service for advanced use cases.\n *\n * @example\n * ```ts\n * @Injectable()\n * class MyService {\n *   private appService = inject(FastifyApplicationServiceToken)\n *\n *   getServer() {\n *     return this.appService.getServer()\n *   }\n * }\n * ```\n */\nexport const FastifyApplicationServiceToken =\n  InjectionToken.create<FastifyApplicationServiceInterface>(\n    'FastifyApplicationService',\n  )\n","import type {\n  CanActivate,\n  ClassType,\n  ControllerMetadata,\n  HandlerMetadata,\n  ModuleMetadata,\n  ScopedContainer,\n} from '@navios/core'\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\nimport type { ZodTypeProvider } from 'fastify-type-provider-zod'\n\nimport {\n  Container,\n  ErrorResponseProducerService,\n  ExecutionContext,\n  extractControllerMetadata,\n  FrameworkError,\n  GuardRunnerService,\n  HttpException,\n  inject,\n  Injectable,\n  InjectionToken,\n  InstanceResolverService,\n  Logger,\n  runWithRequestId,\n} from '@navios/core'\n\nimport { ZodError } from 'zod/v4'\n\nimport type {\n  FastifyDynamicHandler,\n  FastifyHandlerAdapterInterface,\n  FastifyHandlerResult,\n  FastifyStaticHandler,\n} from '../adapters/index.mjs'\n\nimport { FastifyExecutionContext } from '../interfaces/index.mjs'\nimport { FastifyReplyToken, FastifyRequestToken } from '../tokens/index.mjs'\n\nimport '../types/fastify.mjs'\n\ntype PreHandler = (\n  request: FastifyRequest,\n  reply: FastifyReply,\n) => Promise<void>\ntype RouteHandler = (\n  request: FastifyRequest,\n  reply: FastifyReply,\n) => Promise<any>\n\ninterface RouteHandlers {\n  preHandler?: PreHandler\n  handler: RouteHandler\n}\n\n/**\n * Service responsible for adapting Navios controllers to Fastify route handlers.\n *\n * This service processes controller metadata, sets up route handlers with\n * Fastify's routing system, integrates with guards, and handles request/response\n * lifecycle. It bridges the gap between Navios's controller decorators and\n * Fastify's native routing system, including schema-based route registration.\n *\n * @example\n * ```ts\n * // This service is used automatically by the Fastify adapter\n * // Controllers are automatically registered when modules are initialized\n * @Module({\n *   controllers: [UserController],\n * })\n * class AppModule {}\n * ```\n */\n@Injectable()\nexport class FastifyControllerAdapterService {\n  private guardRunner = inject(GuardRunnerService)\n  private container = inject(Container)\n  private instanceResolver = inject(InstanceResolverService)\n  private errorProducer = inject(ErrorResponseProducerService)\n  private logger = inject(Logger, {\n    context: FastifyControllerAdapterService.name,\n  })\n\n  /**\n   * Sets up route handlers for a controller.\n   *\n   * This method processes all endpoints defined in a controller, creates\n   * appropriate route handlers using the configured adapter services,\n   * and registers them with Fastify's routing system. Routes with schemas\n   * are registered with Fastify's type provider for enhanced type safety.\n   *\n   * @param controller - The controller class to set up.\n   * @param instance - The Fastify instance to register routes on.\n   * @param moduleMetadata - Metadata about the module containing the controller.\n   *\n   * @throws {Error} If an endpoint is malformed (missing URL or adapter token).\n   */\n  async setupController(\n    controller: ClassType,\n    instance: FastifyInstance,\n    moduleMetadata: ModuleMetadata,\n  ) {\n    const controllerMetadata = extractControllerMetadata(controller)\n    for (const endpoint of controllerMetadata.endpoints) {\n      const { classMethod, url, httpMethod, adapterToken } = endpoint\n\n      if (!url || !adapterToken) {\n        throw new Error(\n          `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`,\n        )\n      }\n      const adapter = await this.container.get(\n        adapterToken as InjectionToken<FastifyHandlerAdapterInterface>,\n      )\n\n      // Pre-resolve guards (reversed order: module → controller → endpoint)\n      const guards = this.guardRunner.makeContext(\n        moduleMetadata,\n        controllerMetadata,\n        endpoint,\n      )\n      const guardResolution =\n        await this.instanceResolver.resolveMany<CanActivate>(\n          Array.from(guards).reverse() as ClassType[],\n        )\n\n      const hasSchema = adapter.hasSchema?.(endpoint) ?? false\n      const handlerResult = await adapter.provideHandler(controller, endpoint)\n      const { preHandler, handler } = this.wrapHandler(\n        handlerResult,\n        guardResolution,\n        moduleMetadata,\n        controllerMetadata,\n        endpoint,\n      )\n\n      if (hasSchema) {\n        instance.withTypeProvider<ZodTypeProvider>().route({\n          method: httpMethod,\n          url: url.replaceAll('$', ':'),\n          schema: adapter.provideSchema?.(endpoint) ?? {},\n          preHandler,\n          handler,\n        })\n      } else {\n        instance.route({\n          method: httpMethod,\n          url: url.replaceAll('$', ':'),\n          preHandler,\n          handler,\n        })\n      }\n\n      this.logger.debug(\n        `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`,\n      )\n    }\n  }\n\n  /**\n   * Creates a scoped container and attaches it to the request.\n   * Used when handler or guards need request-scoped resolution.\n   * @private\n   */\n  private createRequestContainer(\n    request: FastifyRequest,\n    reply: FastifyReply,\n  ): ScopedContainer {\n    const container = this.container.beginRequest(request.id)\n    request.scopedContainer = container\n    container.addInstance(FastifyRequestToken, request)\n    container.addInstance(FastifyReplyToken, reply)\n    return container\n  }\n\n  /**\n   * Creates execution context and optionally adds it to container.\n   * @private\n   */\n  private createExecutionContext(\n    request: FastifyRequest,\n    reply: FastifyReply,\n    moduleMetadata: ModuleMetadata,\n    controllerMetadata: ControllerMetadata,\n    endpoint: HandlerMetadata,\n    container?: ScopedContainer,\n  ): FastifyExecutionContext {\n    const context = new FastifyExecutionContext(\n      moduleMetadata,\n      controllerMetadata,\n      endpoint,\n      request,\n      reply,\n    )\n    if (container) {\n      container.addInstance(ExecutionContext, context)\n    }\n    return context\n  }\n\n  /**\n   * Creates a static handler wrapper (no scoped container needed).\n   * @private\n   */\n  private makeStaticHandler(handlerResult: FastifyStaticHandler): RouteHandler {\n    return async (request, reply) => {\n      if (reply.sent) return\n      try {\n        return await runWithRequestId(request.id, () =>\n          handlerResult.handler(request, reply),\n        )\n      } catch (error) {\n        return this.handleError(error, reply)\n      }\n    }\n  }\n\n  /**\n   * Creates a dynamic handler wrapper (uses scoped container from request).\n   * @private\n   */\n  private makeDynamicHandler(\n    handlerResult: FastifyDynamicHandler,\n  ): RouteHandler {\n    return async (request, reply) => {\n      if (reply.sent) return\n      try {\n        return await runWithRequestId(request.id, () =>\n          handlerResult.handler(request.scopedContainer!, request, reply),\n        )\n      } catch (error) {\n        return this.handleError(error, reply)\n      }\n    }\n  }\n\n  /**\n   * Creates a preHandler that runs static guards.\n   * @private\n   */\n  private makeStaticGuardsPreHandler(\n    guardInstances: CanActivate[],\n    moduleMetadata: ModuleMetadata,\n    controllerMetadata: ControllerMetadata,\n    endpoint: HandlerMetadata,\n    setupContainer: boolean,\n  ): PreHandler {\n    return async (request, reply) => {\n      try {\n        if (setupContainer) {\n          this.createRequestContainer(request, reply)\n        }\n        await runWithRequestId(request.id, async () => {\n          const context = this.createExecutionContext(\n            request,\n            reply,\n            moduleMetadata,\n            controllerMetadata,\n            endpoint,\n            request.scopedContainer,\n          )\n          await this.guardRunner.runGuardsStatic(guardInstances, context)\n        })\n      } catch (error) {\n        return this.handleError(error, reply)\n      }\n    }\n  }\n\n  /**\n   * Creates a preHandler that runs dynamic guards (needs scoped container).\n   * If endContainerAfter=true, container is ended in finally block.\n   * @private\n   */\n  private makeDynamicGuardsPreHandler(\n    guards: Set<ClassType>,\n    moduleMetadata: ModuleMetadata,\n    controllerMetadata: ControllerMetadata,\n    endpoint: HandlerMetadata,\n  ): PreHandler {\n    return async (request, reply) => {\n      const container = this.createRequestContainer(request, reply)\n\n      try {\n        await runWithRequestId(request.id, async () => {\n          const context = this.createExecutionContext(\n            request,\n            reply,\n            moduleMetadata,\n            controllerMetadata,\n            endpoint,\n            container,\n          )\n          await this.guardRunner.runGuards(guards as any, context, container)\n        })\n      } catch (error) {\n        return this.handleError(error, reply)\n      }\n    }\n  }\n\n  /**\n   * Wraps a route handler with request context, guards, and error handling.\n   *\n   * This method creates route handlers using one of five paths:\n   * 1. Static handler + no guards: Direct handler call (fastest)\n   * 2. Static handler + static guards: preHandler runs guards, handler is direct\n   * 3. Static guards + dynamic handler: preHandler creates container and runs guards\n   * 4. Dynamic guards + static handler: preHandler creates container, runs guards, ends container\n   * 5. Dynamic guards + dynamic handler: preHandler creates container, runs guards, onResponse ends container\n   *\n   * @param handlerResult - The handler result from the adapter service.\n   * @param guardResolution - Pre-resolved guards or resolver function.\n   * @param moduleMetadata - Metadata about the module.\n   * @param controllerMetadata - Metadata about the controller.\n   * @param endpoint - Metadata about the endpoint handler.\n   * @returns Route handlers with optional preHandler.\n   * @private\n   */\n  private wrapHandler(\n    handlerResult: FastifyHandlerResult,\n    guardResolution: {\n      cached: boolean\n      instances: CanActivate[] | null\n      classTypes: ClassType[]\n    },\n    moduleMetadata: ModuleMetadata,\n    controllerMetadata: ControllerMetadata,\n    endpoint: HandlerMetadata,\n  ): RouteHandlers {\n    const hasGuards = guardResolution.classTypes.length > 0\n    const guardsAreStatic = guardResolution.cached\n    const handlerIsStatic = handlerResult.isStatic\n\n    // Path 1: No guards, static handler (fastest path)\n    if (!hasGuards && handlerIsStatic) {\n      return {\n        handler: this.makeStaticHandler(handlerResult),\n      }\n    }\n\n    // Path 2: Static guards, static handler\n    if (hasGuards && guardsAreStatic && handlerIsStatic) {\n      return {\n        preHandler: this.makeStaticGuardsPreHandler(\n          guardResolution.instances!,\n          moduleMetadata,\n          controllerMetadata,\n          endpoint,\n          false, // no container needed\n        ),\n        handler: this.makeStaticHandler(handlerResult),\n      }\n    }\n\n    // Path 3: Static guards, dynamic handler\n    if (hasGuards && guardsAreStatic && !handlerIsStatic) {\n      return {\n        preHandler: this.makeStaticGuardsPreHandler(\n          guardResolution.instances!,\n          moduleMetadata,\n          controllerMetadata,\n          endpoint,\n          true, // setup container for handler\n        ),\n        handler: this.makeDynamicHandler(handlerResult),\n      }\n    }\n\n    // Path 4: Dynamic guards, static handler\n    if (hasGuards && !guardsAreStatic && handlerIsStatic) {\n      return {\n        preHandler: this.makeDynamicGuardsPreHandler(\n          new Set(guardResolution.classTypes),\n          moduleMetadata,\n          controllerMetadata,\n          endpoint,\n        ),\n        handler: this.makeStaticHandler(handlerResult),\n      }\n    }\n\n    // Path 5: Dynamic guards + dynamic handler (or no guards + dynamic handler)\n    const guards = new Set(guardResolution.classTypes)\n    return {\n      preHandler: hasGuards\n        ? this.makeDynamicGuardsPreHandler(\n            guards,\n            moduleMetadata,\n            controllerMetadata,\n            endpoint,\n          )\n        : async (request, reply) => {\n            // No guards, just setup container\n            this.createRequestContainer(request, reply)\n          },\n      handler: this.makeDynamicHandler(handlerResult as FastifyDynamicHandler),\n    }\n  }\n\n  /**\n   * Handles errors and converts them to appropriate HTTP responses.\n   * Uses ErrorResponseProducerService to produce RFC 7807 compliant responses.\n   * @private\n   */\n  private handleError(error: unknown, reply: FastifyReply) {\n    let errorResponse\n\n    if (error instanceof HttpException) {\n      // For HttpException, preserve original response format for backwards compatibility\n      return reply.status(error.statusCode).send(error.response)\n    } else if (error instanceof ZodError) {\n      errorResponse = this.errorProducer.respond(\n        FrameworkError.ValidationError,\n        error,\n      )\n    } else {\n      // Log unexpected errors\n      const err = error as Error\n      this.logger.error(`Error: ${err.message}`, err)\n      errorResponse = this.errorProducer.handleUnknown(error)\n    }\n\n    return reply\n      .status(errorResponse.statusCode)\n      .type('application/problem+json')\n      .send(errorResponse.payload)\n  }\n}\n","import type { FastifySchemaCompiler } from 'fastify'\nimport type { $ZodType } from 'zod/v4/core'\n\nimport { Injectable } from '@navios/core'\n\nimport { safeParse } from 'zod/v4/core'\n\n@Injectable()\nexport class FastifyValidatorCompilerService {\n  errorCompiler: FastifySchemaCompiler<$ZodType> =\n    ({ schema }) =>\n    (data) => {\n      const result = safeParse(schema, data)\n      if (result.error) {\n        return {\n          error: result.error,\n        }\n      }\n\n      return { value: result.data }\n    }\n}\n","import { Container, inject, Injectable, Logger } from '@navios/core'\n\n@Injectable()\nexport class PinoWrapper {\n  protected container = inject(Container)\n  protected logger = inject(Logger)\n\n  fatal(message: any, ...optionalParams: any[]) {\n    if (this.logger.fatal === undefined) {\n      return this.error(message, ...optionalParams)\n    }\n    this.logger.fatal(message, ...optionalParams)\n  }\n\n  error(message: any, ...optionalParams: any[]) {\n    this.logger.error(message, ...optionalParams)\n  }\n\n  warn(message: any, ...optionalParams: any[]) {\n    this.logger.warn(message, ...optionalParams)\n  }\n\n  info() {\n    // We don't want to populate the logs with the original fastify logs\n    // this.logger.debug?.('INFO', message, ...optionalParams)\n  }\n\n  debug(message: any, ...optionalParams: any[]) {\n    this.logger.debug?.(message, ...optionalParams)\n  }\n\n  trace(message: any, ...optionalParams: any[]) {\n    this.logger.verbose?.(message, ...optionalParams)\n  }\n\n  silent() {\n    // noop\n  }\n\n  child(options: any) {\n    const keys = Object.keys(options)\n    let newContext = this.logger['context'] ?? ''\n    if (keys.length > 1) {\n      newContext = `${this.logger['context'] ?? ''}:${JSON.stringify(options)}`\n    }\n    const loggerPromise = this.container.get(Logger, {\n      context: newContext,\n    })\n    const newPinoWrapper = Object.create(PinoWrapper.prototype)\n    newPinoWrapper.container = this.container\n    newPinoWrapper.logger = this.logger\n    loggerPromise.then((logger) => {\n      newPinoWrapper.logger = logger\n    })\n    return newPinoWrapper\n  }\n\n  get level(): any {\n    if ('level' in this.logger && this.logger.level) {\n      return this.logger.level\n    }\n    if (\n      'logLevels' in this.logger &&\n      this.logger.logLevels &&\n      Array.isArray(this.logger.logLevels)\n    ) {\n      return this.logger.logLevels.find((level) => level !== 'verbose')\n    }\n    return 'warn'\n  }\n}\n","import type { FastifyCorsOptions } from '@fastify/cors'\nimport type { FastifyMultipartOptions } from '@fastify/multipart'\nimport type { ModuleMetadata } from '@navios/core'\nimport type {\n  FastifyInstance,\n  FastifyListenOptions,\n  FastifyReply,\n  FastifyRequest,\n  FastifyServerOptions,\n} from 'fastify'\n\nimport {\n  Container,\n  ErrorResponseProducerService,\n  FrameworkError,\n  HttpException,\n  inject,\n  Injectable,\n  Logger,\n} from '@navios/core'\n\nimport cors from '@fastify/cors'\nimport multipart from '@fastify/multipart'\nimport { fastify } from 'fastify'\nimport { serializerCompiler } from 'fastify-type-provider-zod'\nimport { ZodError } from 'zod/v4'\nimport { $ZodError } from 'zod/v4/core'\n\nimport type {\n  FastifyApplicationOptions,\n  FastifyApplicationServiceInterface,\n} from '../interfaces/application.interface.mjs'\n\nimport { FastifyApplicationServiceToken } from '../tokens/index.mjs'\nimport { FastifyServerToken } from '../tokens/server.token.mjs'\nimport { FastifyControllerAdapterService } from './controller-adapter.service.mjs'\nimport { FastifyValidatorCompilerService } from './fastify-validator-compiler.service.mjs'\nimport { PinoWrapper } from './pino-wrapper.mjs'\n\n/**\n * Fastify HTTP adapter service implementation for Navios.\n *\n * This service provides the core HTTP server functionality for Navios applications\n * running on the Fastify runtime. It handles server initialization, route registration,\n * request handling, CORS configuration, multipart support, and server lifecycle management.\n *\n * @example\n * ```ts\n * const app = await NaviosFactory.create(AppModule, {\n *   adapter: defineFastifyEnvironment(),\n * })\n *\n * app.configure({\n *   logger: true,\n *   trustProxy: true,\n * })\n *\n * app.enableCors({ origin: true })\n * app.enableMultipart({ limits: { fileSize: 10 * 1024 * 1024 } })\n *\n * await app.init()\n * await app.listen({ port: 3000, host: '0.0.0.0' })\n * ```\n *\n * @implements {FastifyApplicationServiceInterface}\n */\n@Injectable({\n  token: FastifyApplicationServiceToken,\n})\nexport class FastifyApplicationService implements FastifyApplicationServiceInterface {\n  private logger = inject(Logger, {\n    context: FastifyApplicationService.name,\n  })\n  protected container = inject(Container)\n  private errorProducer = inject(ErrorResponseProducerService)\n  private validatorCompiler = inject(FastifyValidatorCompilerService)\n  private server: FastifyInstance | null = null\n  private controllerAdapter = inject(FastifyControllerAdapterService)\n  private globalPrefix: string = ''\n\n  private corsOptions: FastifyCorsOptions | null = null\n  private multipartOptions: FastifyMultipartOptions | true | null = null\n  private configureOptions: Partial<FastifyApplicationOptions> = {}\n\n  /**\n   * Sets up the Fastify HTTP adapter with the provided options.\n   *\n   * This method is called during application initialization.\n   * It creates the Fastify instance, configures logging, and prepares the server\n   * for route registration.\n   *\n   * @param options - Fastify server configuration options including logger settings,\n   * trust proxy configuration, and other Fastify-specific options.\n   *\n   * @example\n   * ```ts\n   * app.configure({\n   *   logger: true,\n   *   trustProxy: true,\n   *   disableRequestLogging: false,\n   * })\n   * await app.init()\n   * ```\n   */\n  async setupAdapter(options: FastifyApplicationOptions): Promise<void> {\n    const mergedOptions = { ...options, ...this.configureOptions }\n    const { logger, ...fastifyOptions } = mergedOptions\n    if (logger) {\n      const serverOptions = fastifyOptions as FastifyServerOptions\n      if (typeof logger === 'boolean') {\n        if (!logger) {\n          serverOptions.logger = false\n        }\n      } else {\n        serverOptions.loggerInstance = await this.container.get(PinoWrapper)\n      }\n      this.server = fastify(serverOptions)\n    } else {\n      this.server = fastify({\n        ...fastifyOptions,\n        loggerInstance: await this.container.get(PinoWrapper),\n      } as FastifyServerOptions)\n    }\n    await this.initServer()\n  }\n\n  /**\n   * Initializes the Fastify server instance and configures plugins.\n   *\n   * This method is called automatically during server setup. It configures\n   * error handlers, not found handlers, schema validators, and registers\n   * the server instance in the dependency injection container.\n   */\n  async initServer(): Promise<void> {\n    this.configureFastifyInstance()\n    this.registerFastifyInstance()\n    await this.configurePlugins()\n  }\n\n  /**\n   * Waits for the Fastify server to be ready.\n   *\n   * This method ensures all plugins are registered and the server is ready\n   * to accept connections before starting to listen.\n   */\n  async ready(): Promise<void> {\n    await this.server!.ready()\n  }\n\n  /**\n   * Sets a global prefix for all routes.\n   *\n   * This prefix will be prepended to all registered route paths. Useful for\n   * API versioning or organizing routes under a common path.\n   *\n   * @param prefix - The prefix to prepend to all routes (e.g., '/api/v1').\n   * Should start with a forward slash.\n   *\n   * @example\n   * ```ts\n   * app.setGlobalPrefix('/api/v1')\n   * // All routes will be prefixed with /api/v1\n   * ```\n   */\n  setGlobalPrefix(prefix: string): void {\n    this.globalPrefix = prefix\n  }\n\n  /**\n   * Gets the current global prefix for all routes.\n   *\n   * @returns The global prefix string, or empty string if no prefix is set.\n   *\n   * @example\n   * ```ts\n   * app.setGlobalPrefix('/api/v1')\n   * console.log(app.getGlobalPrefix()) // '/api/v1'\n   * ```\n   */\n  getGlobalPrefix(): string {\n    return this.globalPrefix\n  }\n\n  /**\n   * Gets the underlying Fastify server instance.\n   *\n   * This allows direct access to the Fastify instance for advanced use cases,\n   * such as registering custom plugins, hooks, or decorators.\n   *\n   * @returns The Fastify server instance.\n   * @throws {Error} If the server has not been initialized yet.\n   *\n   * @example\n   * ```ts\n   * const fastify = app.getServer()\n   * await fastify.register(require('@fastify/static'), {\n   *   root: path.join(__dirname, 'public'),\n   * })\n   * ```\n   */\n  getServer(): FastifyInstance {\n    if (!this.server) {\n      throw new Error('Server is not initialized. Call init() first.')\n    }\n    return this.server\n  }\n\n  async onModulesInit(modules: Map<string, ModuleMetadata>): Promise<void> {\n    const promises: PromiseLike<any>[] = []\n    for (const [_moduleName, moduleMetadata] of modules) {\n      if (\n        !moduleMetadata.controllers ||\n        moduleMetadata.controllers.size === 0\n      ) {\n        continue\n      }\n      promises.push(\n        this.server!.register(\n          async (instance, _opts) => {\n            for (const controller of moduleMetadata.controllers) {\n              await this.controllerAdapter.setupController(\n                controller,\n                instance,\n                moduleMetadata,\n              )\n            }\n          },\n          {\n            prefix: this.globalPrefix,\n          },\n        ),\n      )\n    }\n\n    await Promise.all(promises)\n  }\n\n  /**\n   * Configures Fastify instance with error handlers, validators, and serializers.\n   *\n   * Sets up:\n   * - Global error handler for HttpException and other errors\n   * - Not found handler for unmatched routes\n   * - Zod-based validator and serializer compilers\n   *\n   * @private\n   */\n  configureFastifyInstance(): void {\n    this.server!.setErrorHandler(\n      (error: unknown, request: FastifyRequest, reply: FastifyReply) => {\n        if (error instanceof HttpException) {\n          // For HttpException, preserve original response format for backwards compatibility\n          return reply.status(error.statusCode).send(error.response)\n        } else if (error instanceof ZodError || error instanceof $ZodError) {\n          const errorResponse = this.errorProducer.respond(\n            FrameworkError.ValidationError,\n            error,\n          )\n          return reply\n            .status(errorResponse.statusCode)\n            .type('application/problem+json')\n            .send(errorResponse.payload)\n        } else {\n          this.logger.error(\n            `Error occurred: ${error instanceof Error ? error.message : 'Unknown error'} on ${request.url}`,\n            error,\n          )\n          const errorResponse = this.errorProducer.respond(\n            FrameworkError.InternalServerError,\n            error,\n          )\n          return reply\n            .status(errorResponse.statusCode)\n            .type('application/problem+json')\n            .send(errorResponse.payload)\n        }\n      },\n    )\n\n    this.server!.setNotFoundHandler(\n      (req: FastifyRequest, reply: FastifyReply) => {\n        this.logger.warn(`Route not found: [${req.method}] ${req.url}`)\n        const errorResponse = this.errorProducer.respond(\n          FrameworkError.NotFound,\n          null,\n          `Route [${req.method}] ${req.url} not found`,\n        )\n        return reply\n          .status(errorResponse.statusCode)\n          .type('application/problem+json')\n          .send(errorResponse.payload)\n      },\n    )\n\n    // Add request decoration for scoped container storage between hooks\n    this.server!.decorateRequest('scopedContainer', undefined)\n\n    // Global onResponse hook for non-blocking container cleanup\n    this.server!.addHook('onResponse', async (request) => {\n      if (request.scopedContainer) {\n        request.scopedContainer.endRequest().catch((err: any) => {\n          this.logger.error(`Error ending request context: ${err.message}`, err)\n        })\n      }\n    })\n\n    // Add schema validator and serializer\n    this.server!.setValidatorCompiler(this.validatorCompiler.errorCompiler)\n    this.server!.setSerializerCompiler(serializerCompiler)\n  }\n\n  /**\n   * Configures and registers Fastify plugins (CORS, multipart, etc.).\n   *\n   * This method registers plugins that were configured via `enableCors()`\n   * and `enableMultipart()` methods.\n   *\n   * @private\n   */\n  async configurePlugins(): Promise<void> {\n    if (this.corsOptions) {\n      await this.server!.register(cors, this.corsOptions)\n    }\n\n    if (this.multipartOptions) {\n      await this.configureMultipart(this.multipartOptions)\n    }\n  }\n\n  /**\n   * Configures multipart form data support.\n   *\n   * @param options - Multipart configuration options or `true` for defaults.\n   * @private\n   */\n  async configureMultipart(\n    options: FastifyMultipartOptions | true,\n  ): Promise<void> {\n    if (options) {\n      await this.server!.register(\n        multipart,\n        typeof options === 'object' ? options : {},\n      )\n    }\n  }\n\n  /**\n   * Registers the Fastify instance in the dependency injection container.\n   *\n   * Makes the server instance available for injection via `FastifyServerToken`.\n   *\n   * @private\n   */\n  registerFastifyInstance(): void {\n    this.container.addInstance(FastifyServerToken, this.server!)\n  }\n\n  /**\n   * Enables CORS (Cross-Origin Resource Sharing) support.\n   *\n   * Configures CORS headers for all routes. The options are applied when\n   * the server is initialized.\n   *\n   * @param options - CORS configuration options from `@fastify/cors`.\n   *\n   * @example\n   * ```ts\n   * app.enableCors({\n   *   origin: true, // Allow all origins\n   *   methods: ['GET', 'POST', 'PUT', 'DELETE'],\n   *   credentials: true,\n   * })\n   * ```\n   *\n   * @see {@link https://github.com/fastify/fastify-cors} Fastify CORS plugin documentation\n   */\n  enableCors(options: FastifyCorsOptions): void {\n    this.corsOptions = options\n  }\n\n  /**\n   * Enables multipart form data support for file uploads.\n   *\n   * Configures multipart handling for all routes. The options are applied when\n   * the server is initialized.\n   *\n   * @param options - Multipart configuration options from `@fastify/multipart`.\n   *\n   * @example\n   * ```ts\n   * app.enableMultipart({\n   *   limits: {\n   *     fileSize: 10 * 1024 * 1024, // 10MB\n   *     files: 5, // Max 5 files\n   *   },\n   * })\n   * ```\n   *\n   * @see {@link https://github.com/fastify/fastify-multipart} Fastify Multipart plugin documentation\n   */\n  enableMultipart(options: FastifyMultipartOptions): void {\n    this.multipartOptions = options\n  }\n\n  /**\n   * Starts the Fastify HTTP server and begins listening for incoming requests.\n   *\n   * This method starts the server with the configured routes and options.\n   * The server will handle all registered routes and return 404 for unmatched requests.\n   *\n   * @param options - Server listen options including port and host.\n   * @returns A promise that resolves to the server address string.\n   *\n   * @example\n   * ```ts\n   * const address = await app.listen({\n   *   port: 3000,\n   *   host: '0.0.0.0',\n   * })\n   * console.log(`Server listening on ${address}`)\n   * ```\n   */\n  async listen(options: FastifyListenOptions): Promise<string> {\n    const res = await this.server!.listen(options)\n    this.logger.debug(`Navios is listening on ${res}`)\n    return res\n  }\n\n  /**\n   * Configures the adapter with additional options before initialization.\n   *\n   * Options set via configure() are merged with options passed to\n   * setupAdapter(), with configure() options taking precedence.\n   * Must be called before init().\n   *\n   * @param options - Partial Fastify server configuration options\n   *\n   * @example\n   * ```ts\n   * app.configure({ trustProxy: true, logger: true })\n   * await app.init()\n   * ```\n   */\n  configure(options: Partial<FastifyApplicationOptions>): void {\n    this.configureOptions = { ...this.configureOptions, ...options }\n  }\n\n  /**\n   * Gracefully shuts down the Fastify server.\n   *\n   * This method closes all connections and cleans up resources. Should be called\n   * during application shutdown to ensure proper cleanup.\n   *\n   * @example\n   * ```ts\n   * process.on('SIGTERM', async () => {\n   *   await app.dispose()\n   *   process.exit(0)\n   * })\n   * ```\n   */\n  async dispose(): Promise<void> {\n    await this.server!.close()\n  }\n}\n","import type { AnyInjectableType } from '@navios/core'\n\nimport {\n  AdapterToken,\n  EndpointAdapterToken,\n  HttpAdapterToken,\n  InjectionToken,\n  MultipartAdapterToken,\n  Reply,\n  Request,\n  StreamAdapterToken,\n} from '@navios/core'\n\nimport {\n  FastifyEndpointAdapterService,\n  FastifyMultipartAdapterService,\n  FastifyStreamAdapterService,\n} from './adapters/index.mjs'\nimport { FastifyApplicationService } from './services/index.mjs'\nimport { FastifyReplyToken, FastifyRequestToken } from './tokens/index.mjs'\n\n/**\n * Creates a Fastify adapter environment configuration for Navios.\n *\n * This function sets up the necessary dependency injection tokens and services\n * required to run Navios applications on the Fastify runtime. It configures:\n * - HTTP adapter service for handling HTTP requests\n * - Endpoint adapter for standard REST endpoints\n * - Stream adapter for streaming responses\n * - Multipart adapter for file uploads and form data\n * - Request and Reply tokens for accessing Fastify request/reply objects\n *\n * @returns An object containing the token mappings for the Fastify adapter.\n * This object should be passed to `NaviosFactory.create()` as the `adapter` option.\n *\n * @example\n * ```ts\n * import { defineFastifyEnvironment } from '@navios/adapter-fastify'\n * import { NaviosFactory } from '@navios/core'\n *\n * const app = await NaviosFactory.create(AppModule, {\n *   adapter: defineFastifyEnvironment(),\n * })\n * ```\n *\n * @example\n * ```ts\n * // With CORS and multipart support\n * const app = await NaviosFactory.create(AppModule, {\n *   adapter: defineFastifyEnvironment(),\n * })\n *\n * app.enableCors({\n *   origin: true,\n *   methods: ['GET', 'POST', 'PUT', 'DELETE'],\n * })\n *\n * app.enableMultipart({\n *   limits: { fileSize: 10 * 1024 * 1024 }, // 10MB\n * })\n * ```\n *\n * @see {@link FastifyApplicationService} The HTTP adapter service implementation\n * @see {@link FastifyEndpointAdapterService} The endpoint adapter implementation\n * @see {@link FastifyStreamAdapterService} The stream adapter implementation\n * @see {@link FastifyMultipartAdapterService} The multipart adapter implementation\n */\nexport function defineFastifyEnvironment() {\n  const tokens = new Map<InjectionToken<any, undefined>, AnyInjectableType>([\n    [AdapterToken, FastifyApplicationService],\n    [HttpAdapterToken, FastifyApplicationService],\n    [EndpointAdapterToken, FastifyEndpointAdapterService],\n    [StreamAdapterToken, FastifyStreamAdapterService],\n    [MultipartAdapterToken, FastifyMultipartAdapterService],\n    [Request, FastifyRequestToken],\n    [Reply, FastifyReplyToken],\n  ])\n  return {\n    tokens,\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;GAsBA,IAAsBC,uCAAtB,cAEUD,8BAAAA;;;;;;;;IASR,sBACEG,iBACkC;EAClC,MAAMC,SAASD,gBAAgBC;EAC/B,MAAMC,UAA4C,EAAE;AAEpD,MAAID,OAAOE,YACTD,SAAQE,MAAMC,QAAQC,YAAAA;AACpBD,UAAOE,SAASD,QAAQE;IAC1B;AAGF,MAAIP,OAAOQ,cACTP,SAAQE,MAAMC,QAAQC,YAAAA;AACpBD,UAAOK,OAAOJ,QAAQK;IACxB;AAGF,MAAI,KAAKC,aAAaX,OAAAA,CACpBC,SAAQE,MAAMC,QAAQC,YAAAA;AACpBD,UAAOQ,YAAYP,QAAQC;IAC7B;AAGF,SAAOL;;;;;;;IAST,UAAmBF,iBAAoD;EACrE,MAAMC,SAASD,gBAAgBC;AAC/B,SACE,CAAC,CAACA,OAAOQ,iBACT,CAAC,CAACR,OAAOE,eACR,CAAC,CAAC,KAAKY,QAAQC,qBAAqB,CAAC,CAACf,OAAOgB;;;;;;;;;;IAalD,cACEjB,iBACqB;EACrB,MAAMmB,SAA8B,EAAC;EACrC,MAAM,EAAEhB,aAAaM,eAAeQ,gBAAgBjB,gBAAgBC;AAEpE,MAAIE,YACFgB,QAAOC,cAAcjB;AAEvB,MAAIM,cACFU,QAAOR,OAAOF;AAEhB,MAAI,KAAKM,QAAQC,qBAAqBC,YACpCE,QAAOE,WAAW,EAChB,GAAGJ,aACL;AAGF,SAAOE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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