/*! * @Author: richen * @Date: 2026-09-30 13:09:09 * @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'; import { Middleware } from 'koa-compose'; import { Readable } from 'stream'; /** * Alias of @RequestBody * @param {*} * @return {*} */ export declare const Body: typeof RequestBody; /** * Parse request body and cache the result. * Returns cached result synchronously on subsequent calls (avoids microtask overhead). * First call returns a Promise that resolves after parsing. * * @param {KoattyContext} ctx - Koatty context object * @param {PayloadOptions} [options] - Optional payload parsing options * @returns {any} Parsed body (synchronous if cached) or Promise (first parse) */ export declare function bodyParser(ctx: KoattyContext, options?: PayloadOptions): any; /** * Routes HTTP DELETE requests to the specified path. */ export declare const DeleteMapping: (path?: string, routerOptions?: Partial) => (...args: any[]) => any; export declare function encodeSSE(event: SSEEvent): string; /** * HTTP error-negotiation middleware. * * Registered ahead of the router chain so that an error raised anywhere * downstream is written in the representation the client asked for: * * - client explicitly accepts JSON → `application/json` body * (`{ error: { status, code, message } }`); * - anything else → the framework's existing `text/plain` behaviour is kept by * re-throwing, so Koa's `ctx.onerror` produces the response as before. * * Non-HTTP protocols (gRPC, WebSocket) never set an explicit JSON `Accept` in a * way this middleware reacts to, so their error handling is unchanged. */ export declare function errorNegotiation(): Middleware; /** * 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 } /** * Symbol key for uploaded files in parsed multipart body. * Use this key to access files from the parsed body object: * @example * const files = parsedBody[FILE_KEY]; */ export declare const FILE_KEY: unique symbol; /** * 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?: Partial) => (...args: any[]) => any; /** * 获取协议特定配置的工具函数 */ export declare function getProtocolConfig(protocol: T, ext?: Record): ProtocolExtConfigMap[T]; /** * GraphQL 协议特定配置 */ export declare interface GraphQLExtConfig { /** GraphQL Schema 文件路径 */ schemaFile: string; /** 启用 GraphQL Playground。默认值来自安全画像:production/standard 关闭,development 开启;显式配置优先 */ playground?: boolean; /** 启用内省查询。默认值来自安全画像:strict 关闭,standard/development 开启;显式配置优先 */ introspection?: boolean; /** 调试模式,默认false */ debug?: boolean; /** 查询深度限制(内置实现)。默认值来自安全画像(strict 10 / standard 15 / development 20);0 表示关闭 */ depthLimit?: number; /** 查询复杂度限制。默认值来自安全画像(strict 1000 / standard 2000 / development 5000);需要可选包 graphql-query-complexity,配置了但未安装时启动失败 */ 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?: Partial) => (...args: any[]) => any; /** * 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; /** * The status/content-type/body an error should produce for this client. * * 5xx messages are never leaked (they become `Internal Server Error`), matching * Koa's `err.expose` contract. */ export declare function negotiateError(ctx: KoattyContext, err: any): { status: number; contentType: string; body: string; }; /** * 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?: Partial) => (...args: any[]) => any; /** * 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?: Partial) => (...args: any[]) => any; /** * 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; /** * Middleware for parsing request payload (query parameters and request body). * * @param {PayloadOptions} [options] - Configuration options for payload parsing * @returns {Function} Koa middleware function that adds requestParam and requestBody to context * * @example * ```ts * app.use(payload({ * // payload options * })); * ``` */ export declare function payload(options?: PayloadOptions): (ctx: KoattyContext, next: KoattyNext) => Promise; /** * 请求参数选项 */ export declare interface PayloadOptions { extTypes: Record; limit: string; encoding: BufferEncoding; multiples: boolean; keepExtensions: boolean; length?: number; /** * Behavior when the request body cannot be parsed (SEC-02 / ADR-101): * - 'reject' (default): throw an Exception carrying the HTTP status * (400 malformed, 413 too large, 415 unsupported encoding); * - 'empty': legacy behavior, log and fall back to `{}`. * When unset, falls back to `app.security.payload.onParseError`. */ onParseError?: 'reject' | 'empty'; /** * Protocol Buffer 文件路径(用于 gRPC 自动解析) * 如果提供,gRPC payload 解析器将尝试自动解码 */ protoFile?: string; /** Max number of uploaded files per request (multipart). Defaults from the security profile. */ maxFiles?: number; /** Max number of form fields per request (multipart). Defaults from the security profile. */ maxFields?: number; /** Max total size of non-file fields, e.g. '1mb' (multipart). Defaults from the security profile. */ maxFieldsSize?: string; /** Directory for uploaded temp files. Defaults to `os.tmpdir()/koatty-upload-`. */ uploadDir?: string; /** Optional formidable filter to accept/reject parts by mimetype or name. */ fileFilter?: (part: unknown) => boolean | Promise; } /** * 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?: Partial) => (...args: any[]) => any; /** * Whether the request explicitly prefers JSON over plain text. */ export declare function prefersJson(ctx: KoattyContext): boolean; /** * 协议扩展配置联合类型 */ 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?: Partial) => (...args: any[]) => any; /** * Parse and merge query parameters and route parameters from context * @param {KoattyContext} ctx Koatty context object * @param {PayloadOptions} [_options] Optional payload configuration * @returns {Record} Merged object containing query and route parameters */ export declare function queryParser(ctx: KoattyContext, _options?: PayloadOptions): Record; /** * 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[]; }) => ((...args: any[]) => any); /** * 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(app?: object): 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 extends Record { /** 路由前缀 */ 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; } /** * Sanitize an attacker-controlled filename (SEC-05): strip directory * components and path separators so the value can never traverse outside * the intended upload directory. `originalFilename` from multipart requests * must always pass through this helper before being used for storage. */ export declare function safeFilename(name: unknown): string; export declare interface SSEEvent { event?: string; data?: unknown; id?: string; retry?: number; comment?: string; } export declare interface SSEOptions { heartbeatInterval?: number; headers?: Record; onClose?: () => void; } export declare type SSESource = AsyncIterable | ReadableStream | Readable; /** * gRPC 流配置 */ export declare interface StreamConfig { /** 最大并发流数量,默认50 */ maxConcurrentStreams?: number; /** 流超时时间(ms),默认60秒 */ streamTimeout?: number; /** 背压阈值(字节),默认2048 */ backpressureThreshold?: number; /** 是否启用流压缩,默认false */ enableCompression?: boolean; } /** * Stream with backpressure. Prefer a factory so the producer receives the abort * signal before starting work. Arbitrary producers must cooperate with cancellation. */ export declare function streamSSE(ctx: any, source: SSESource | ((signal: AbortSignal) => SSESource | Promise>), options?: SSEOptions): Promise; /** * 验证协议特定配置的工具函数(增强版) */ 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 { }