/*! * @Author: richen * @Date: 2026-04-24 16:20:40 * @License: BSD (3-Clause) * @Copyright (c) - * @HomePage: https://koatty.org/ */ import { Application } from 'koatty_container'; import { IComponent } from 'koatty_core'; import { KoattyApplication } from 'koatty_core'; import { KoattyContext } from 'koatty_core'; import { KoattyNext } from 'koatty_core'; import { KoattyRouter } from 'koatty_core'; /** * Alias of @RequestBody * @param {*} * @return {*} */ export declare const Body: typeof RequestBody; /** * Routes HTTP DELETE requests to the specified path. */ export declare const DeleteMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * Get parsed upload file object. * * @export * @param {string} [name] * @param {any} [defaultValue] - Default value if file is undefined * @returns */ declare function File_2(name?: string, defaultValue?: any): ParameterDecorator; export { File_2 as File } /** * Get query-string parameters (take value from ctx.query). * * @export * @param {string} [name] * @param {any} [defaultValue] - Default value if query parameter is undefined * @returns */ export declare function Get(name?: string, defaultValue?: any): ParameterDecorator; /** * Routes HTTP GET requests to the specified path. */ export declare const GetMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * 获取协议特定配置的工具函数 */ export declare function getProtocolConfig(protocol: T, ext?: Record): ProtocolExtConfigMap[T]; /** * GraphQL 协议特定配置 */ export declare interface GraphQLExtConfig { /** GraphQL Schema 文件路径 */ schemaFile: string; /** 启用 GraphQL Playground,默认false */ playground?: boolean; /** 启用内省查询,默认true */ introspection?: boolean; /** 调试模式,默认false */ debug?: boolean; /** 查询深度限制,默认10 */ depthLimit?: number; /** 查询复杂度限制,默认1000 */ complexityLimit?: number; /** 自定义标量类型 */ customScalars?: Record; /** 中间件配置 */ middlewares?: any[]; } /** * gRPC 协议特定配置 */ export declare interface GrpcExtConfig { /** Protocol Buffer 文件路径 */ protoFile: string; /** 连接池大小,默认10 */ poolSize?: number; /** 批处理大小,默认10 */ batchSize?: number; /** 流配置 */ streamConfig?: StreamConfig; /** gRPC 服务器选项 */ serverOptions?: Record; /** 是否启用反射,默认false */ enableReflection?: boolean; } /** * Get request header. * * @export * @param {string} [name] * @param {any} [defaultValue] - Default value if header is undefined * @returns */ export declare function Header(name?: string, defaultValue?: any): ParameterDecorator; /** * Routes HTTP HEAD requests to the specified path. */ export declare const HeadMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * HTTP 协议特定配置(目前为空,预留扩展) */ export declare interface HttpExtConfig { /** 自定义HTTP选项 */ [key: string]: any; } /** * Router factory interface */ export declare interface IRouterFactory { create(protocol: string, app: KoattyApplication, options: RouterOptions): KoattyRouter; register(protocol: string, routerClass: RouterConstructor): void; getSupportedProtocols(): string[]; } /** * Router middleware manager interface * Defines the contract for managing router-level middleware */ export declare interface IRouterMiddlewareManager { register(config: MiddlewareConfig): Promise; unregister(nameOrInstanceId: string): boolean; getMiddleware(nameOrInstanceId: string): MiddlewareConfig | null; getMiddlewareByRoute(middlewareName: string, route: string, method?: string): MiddlewareConfig | null; listMiddlewares(): string[]; compose(instanceIds: string[], context?: MiddlewareExecutionContext): MiddlewareFunction; createGroup(groupName: string, middlewareNames: string[]): Promise; } export declare const MAPPING_KEY = "MAPPING_KEY"; /** * Middleware builder for fluent API */ export declare class MiddlewareBuilder { name(name: string): this; priority(priority: number): this; enabled(enabled: boolean): this; middleware(middleware: MiddlewareFunction): this; condition(condition: MiddlewareCondition): this; metadata(key: string, value: unknown): this; build(): MiddlewareConfig; register(app: Application): void; } /** * Middleware condition */ export declare interface MiddlewareCondition { type: 'path' | 'method' | 'header' | 'custom'; value: string | RegExp | ((ctx: KoattyContext) => boolean); operator?: 'equals' | 'contains' | 'matches' | 'custom'; } /** * Middleware configuration */ export declare interface MiddlewareConfig { name: string; instanceId?: string; middleware: MiddlewareFunction | Function; priority?: number; enabled?: boolean; conditions?: MiddlewareCondition[]; metadata?: Record; middlewareConfig?: { [key: string]: unknown; }; } /** * Enhanced middleware configuration for decorators */ export declare interface MiddlewareDecoratorConfig { middleware: Function; priority?: number; enabled?: boolean; conditions?: MiddlewareCondition[]; metadata?: Record; } /** * Middleware execution context */ export declare interface MiddlewareExecutionContext { route?: string; method?: string; protocol?: string; metadata?: Record; } /** * Middleware function type */ export declare type MiddlewareFunction = (ctx: KoattyContext, next: KoattyNext) => Promise | T; /** * get instance of Router using Factory Pattern * * @export * @param {KoattyApplication} app * @param {RouterOptions} options * @returns {*} {{ router: KoattyRouter, factory: RouterFactory }} */ export declare function NewRouter(app: KoattyApplication, opt?: RouterOptions): { router: KoattyRouter; factory: RouterFactory; }; /** * Routes HTTP OPTIONS requests to the specified path. */ export declare const OptionsMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * Alias of @RequestParam * @param {*} * @return {*} */ export declare const Param: typeof RequestParam; /** * Routes HTTP PATCH requests to the specified path. */ export declare const PatchMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * Get path variable (take value from ctx.params). * * @export * @param {string} [name] params name * @param {any} [defaultValue] - Default value if path variable is undefined * @returns */ export declare function PathVariable(name?: string, defaultValue?: any): ParameterDecorator; /** * 请求参数选项 */ declare interface PayloadOptions { extTypes: Record; limit: string; encoding: BufferEncoding; multiples: boolean; keepExtensions: boolean; length?: number; /** * Protocol Buffer 文件路径(用于 gRPC 自动解析) * 如果提供,gRPC payload 解析器将尝试自动解码 */ protoFile?: string; } /** * Get parsed POST/PUT... body. * * @export * @param {string} [name] * @param {any} [defaultValue] - Default value if body parameter is undefined * @returns */ export declare function Post(name?: string, defaultValue?: any): ParameterDecorator; /** * Routes HTTP POST requests to the specified path. */ export declare const PostMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * 协议扩展配置联合类型 */ export declare type ProtocolExtConfig = WebSocketExtConfig | GrpcExtConfig | GraphQLExtConfig | HttpExtConfig; /** * 协议扩展配置映射 */ export declare interface ProtocolExtConfigMap { http: HttpExtConfig; https: HttpExtConfig; http2: HttpExtConfig; http3: HttpExtConfig; ws: WebSocketExtConfig; wss: WebSocketExtConfig; grpc: GrpcExtConfig; graphql: GraphQLExtConfig; } /** * Routes HTTP PUT requests to the specified path. */ export declare const PutMapping: (path?: string, routerOptions?: RouterOption) => MethodDecorator; /** * Decorator for auto-registering middlewares */ export declare function RegisterMiddleware(app: Application, config: Omit): (target: object, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor; /** * Decorator for auto-registering custom routers */ export declare function RegisterRouter(protocol: string): (target: T) => T; /** * Get parsed request body as a flat object. * For multipart requests, use FILE_KEY symbol from payload/interface to access uploaded files. * * @export * @returns Flat body object. Files (if any) accessible via body[FILE_KEY]. */ export declare function RequestBody(): ParameterDecorator; /** * Routes HTTP requests to the specified path with enhanced middleware support. * * @param {string} [path="/"] * @param {RequestMethod} [reqMethod=RequestMethod.GET] * @param {{ * routerName?: string; * middleware?: Function[] | MiddlewareDecoratorConfig[]; * }} [routerOptions={}] * @returns {*} {MethodDecorator} */ export declare const RequestMapping: (path?: string, reqMethod?: RequestMethod, routerOptions?: { routerName?: string; middleware?: Function[] | MiddlewareDecoratorConfig[]; }) => MethodDecorator; /** * http request methods * * @export * @var RequestMethod */ export declare enum RequestMethod { "GET" = "get", "POST" = "post", "PUT" = "put", "DELETE" = "delete", "PATCH" = "patch", "ALL" = "all", "OPTIONS" = "options", "HEAD" = "head" } /** * Get parsed query-string and path variable(koa ctx.query and ctx.params), * and set as an object. * * @export * @returns {ParameterDecorator} */ export declare function RequestParam(): ParameterDecorator; /** * Router Component * Responsible for initializing and managing routing * * Implements IComponent interface (base interface) * * Event bindings: * - loadRouter: Initialize router * - appStop: Cleanup router resources */ export declare class RouterComponent implements IComponent { events: Record; /** * Initialize router and load routes * * This method handles the complete router initialization: * 1. Create router instance(s) for configured protocol(s) * 2. Bind router to app.router * 3. Load controller routes into router */ initRouter(app: KoattyApplication): Promise; /** * Load controller routes into router * * @param app - Koatty application instance */ /** * Cleanup router resources on app stop * * NOTE: Original app.once("appStop", ...) listener in router.ts * is now unified to be handled by @OnEvent(AppEvent.appStop) decorator */ cleanup(_app: KoattyApplication): Promise; } /** * Router constructor type */ export declare type RouterConstructor = new (app: KoattyApplication, options?: RouterOptions) => KoattyRouter; /** * Router factory implementation */ export declare class RouterFactory implements IRouterFactory { /** * Get singleton instance */ static getInstance(): RouterFactory; /** * Initialize default routers */ /** * Create router instance */ create(protocol: string, app: KoattyApplication, options: RouterOptions): KoattyRouter; /** * Register custom router */ register(protocol: string, routerClass: RouterConstructor): void; /** * Unregister router */ unregister(protocol: string): boolean; /** * Get supported protocols */ getSupportedProtocols(): string[]; /** * Check if protocol is supported */ isSupported(protocol: string): boolean; /** * Get router class for protocol */ getRouterClass(protocol: string): RouterConstructor | undefined; /** * Clear all registered routers (for testing) */ clear(): void; /** * Reset to default routers */ reset(): void; /** * Shutdown all active routers (for graceful shutdown) * This method should be called when the application receives termination signal * * IMPORTANT: This method uses flags to ensure it only runs once even if called * multiple times in multi-protocol environments where each NewRouter() call * registers an appStop listener. */ shutdownAll(): Promise; /** * Get count of active routers */ getActiveRouterCount(): number; /** * Get active routers list */ getActiveRouters(): KoattyRouter[]; } /** * Router factory builder for advanced configuration */ export declare class RouterFactoryBuilder { /** * Add custom router */ addRouter(protocol: string, routerClass: RouterConstructor): this; /** * Exclude default router */ excludeDefault(protocol: string): this; /** * Build factory with custom configuration */ build(): IRouterFactory; } /** * Router middleware manager implementation * Manages router-level middleware registration, composition, and conditional execution */ export declare class RouterMiddlewareManager implements IRouterMiddlewareManager { /** * Private constructor to enforce singleton pattern */ /** * Get singleton instance * @returns RouterMiddlewareManager instance */ static getInstance(app: Application): RouterMiddlewareManager; /** * Reset singleton instance (for testing) */ static resetInstance(): void; /** * Get total cache size */ /** * Destroy manager and cleanup resources */ destroy(): void; /** * Register middleware */ register(config: MiddlewareConfig): Promise; /** * Generate unique instance ID using middleware name and route */ /** * Check if the provided function is a middleware class */ /** * Process middleware class to get actual middleware function */ /** * Preprocess conditions for optimized matching */ /** * Preprocess path conditions */ /** * Preprocess method conditions */ /** * Preprocess header conditions */ /** * Unregister middleware by name or instance ID */ unregister(nameOrInstanceId: string): boolean; /** * Get middleware configuration by name or instance ID */ getMiddleware(nameOrInstanceId: string): MiddlewareConfig | null; /** * Get middleware by route and middleware name */ getMiddlewareByRoute(middlewareName: string, route: string, method?: string): MiddlewareConfig | null; /** * Get all middleware instances by name */ getMiddlewareInstances(name: string): MiddlewareConfig[]; /** * List all middlewares */ listMiddlewares(): string[]; /** * Enable/disable middleware by name or instance ID */ setEnabled(nameOrInstanceId: string, enabled: boolean): void; /** * Compose middlewares by instance IDs */ compose(instanceIds: string[], context?: MiddlewareExecutionContext): MiddlewareFunction; /** * Create conditional middleware */ /** * Evaluate middleware conditions */ /** * Evaluate path condition with optimized matching */ /** * Evaluate method condition with caching */ /** * Evaluate header condition with caching */ /** * Evaluate custom condition */ /** * Wrap middleware */ /** * Clear all caches with proper cleanup */ clearCaches(): void; /** * Create middleware group */ createGroup(groupName: string, middlewareNames: string[]): Promise; } /** * Koatty router options with enhanced middleware support * * @export * @interface RouterOption */ export declare interface RouterOption { path?: string; requestMethod: string; routerName?: string; method: string; middleware?: Function[] | MiddlewareDecoratorConfig[]; } /** * RouterOptions * * @export * @interface RouterOptions */ export declare interface RouterOptions { /** 路由前缀 */ prefix: string; /** * Methods which should be supported by the router. */ methods?: string[]; routerPath?: string; /** * Whether or not routing should be case-sensitive. */ sensitive?: boolean; /** * Whether or not routes should matched strictly. * * If strict matching is enabled, the trailing slash is taken into * account when matching routes. */ strict?: boolean; /** server protocol */ protocol?: string; /** * payload options */ payload?: PayloadOptions; /** * 协议特定的扩展配置 * * 各协议的特定参数都放在此字段中: * - WebSocket: { maxFrameSize, heartbeatInterval, maxConnections, ... } * - gRPC: { protoFile, poolSize, batchSize, streamConfig, ... } * - GraphQL: { schemaFile, playground, introspection, ... } * - HTTP/HTTPS: 预留扩展字段 * * @example * ```typescript * ext: { * http: {}, * grpc: { * protoFile: "./proto/service.proto", * poolSize: 10, * streamConfig: { maxConcurrentStreams: 50 } * }, * graphql: { * schemaFile: "./resource/graphql/schema.graphql", * // Optional: Enable HTTP/2 with SSL for GraphQL * // keyFile: "./ssl/server.key", * // crtFile: "./ssl/server.crt", * // ssl: { mode: 'auto', allowHTTP1: true }, * // http2: { maxConcurrentStreams: 100 } * }, * ws: { * maxFrameSize: 1024 * 1024, * heartbeatInterval: 15000, * maxConnections: 1000 * } * } * ``` */ ext?: Record; } /** * gRPC 流配置 */ export declare interface StreamConfig { /** 最大并发流数量,默认50 */ maxConcurrentStreams?: number; /** 流超时时间(ms),默认60秒 */ streamTimeout?: number; /** 背压阈值(字节),默认2048 */ backpressureThreshold?: number; /** 是否启用流压缩,默认false */ enableCompression?: boolean; } /** * 验证协议特定配置的工具函数(增强版) */ export declare function validateProtocolConfig(protocol: string, ext?: Record, env?: string): ValidationResult; /** * 配置验证结果 */ export declare interface ValidationResult { valid: boolean; errors: string[]; warnings: string[]; } /** * WebSocket 协议特定配置 */ export declare interface WebSocketExtConfig { /** 最大分帧大小(字节),默认1MB */ maxFrameSize?: number; /** 分帧处理超时(ms),默认30秒 */ frameTimeout?: number; /** 心跳检测间隔(ms),默认15秒 */ heartbeatInterval?: number; /** 心跳超时时间(ms),默认30秒 */ heartbeatTimeout?: number; /** 最大连接数,默认1000 */ maxConnections?: number; /** 最大缓冲区大小(字节),默认10MB */ maxBufferSize?: number; /** 清理间隔(ms),默认5分钟 */ cleanupInterval?: number; } /** * Helper function to create middleware configuration with advanced features * * @param middleware - The middleware class * @param options - Advanced configuration options * @returns MiddlewareDecoratorConfig * * @example * ```typescript * @GetMapping('/api/users', { * middleware: [ * withMiddleware(AuthMiddleware, { * priority: 100, * conditions: [{ type: 'header', value: 'authorization', operator: 'contains' }] * }), * withMiddleware(RateLimitMiddleware, { * priority: 90, * metadata: { limit: 100, window: 60000 } * }) * ] * }) * ``` */ export declare function withMiddleware(middleware: Function, options?: { priority?: number; enabled?: boolean; conditions?: MiddlewareCondition[]; metadata?: Record; }): MiddlewareDecoratorConfig; export { }