@stacksjs/bun-router 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +397 -0
  3. package/bin/cli.ts +9 -0
  4. package/dist/auth.d.ts +77 -0
  5. package/dist/cache/lru-cache.d.ts +88 -0
  6. package/dist/cache/middleware-memoization.d.ts +101 -0
  7. package/dist/cache/route-cache-warmer.d.ts +125 -0
  8. package/dist/cache/sqlite-cache.d.ts +114 -0
  9. package/dist/cache/streaming-cache.d.ts +86 -0
  10. package/dist/chunk-r15a48wc.js +25448 -0
  11. package/dist/cli/colors.d.ts +12 -0
  12. package/dist/cli/index.d.ts +10 -0
  13. package/dist/cli/middleware.d.ts +31 -0
  14. package/dist/cli/openapi.d.ts +17 -0
  15. package/dist/cli/router.d.ts +15 -0
  16. package/dist/cli/routes.d.ts +30 -0
  17. package/dist/cli/utils.d.ts +68 -0
  18. package/dist/cli.d.ts +0 -0
  19. package/dist/cli.js +3195 -0
  20. package/dist/config.d.ts +274 -0
  21. package/dist/container/container.d.ts +141 -0
  22. package/dist/container/contextual-binding.d.ts +112 -0
  23. package/dist/container/decorators.d.ts +114 -0
  24. package/dist/container/service-provider.d.ts +221 -0
  25. package/dist/development/hot-reload.d.ts +129 -0
  26. package/dist/development/index.d.ts +144 -0
  27. package/dist/development/performance-profiler.d.ts +152 -0
  28. package/dist/development/route-debugger.d.ts +102 -0
  29. package/dist/development/route-inspector.d.ts +142 -0
  30. package/dist/development/typescript-utilities.d.ts +116 -0
  31. package/dist/docs.d.ts +10 -0
  32. package/dist/errors/circuit-breaker.d.ts +138 -0
  33. package/dist/errors/error-handler.d.ts +57 -0
  34. package/dist/errors/error-reporting.d.ts +135 -0
  35. package/dist/errors/exceptions.d.ts +178 -0
  36. package/dist/errors/graceful-degradation.d.ts +130 -0
  37. package/dist/errors/index.d.ts +6 -0
  38. package/dist/errors/router-errors.d.ts +97 -0
  39. package/dist/file-serving/static-files.d.ts +98 -0
  40. package/dist/index.d.ts +10 -0
  41. package/dist/index.js +13417 -0
  42. package/dist/middleware/auth.d.ts +34 -0
  43. package/dist/middleware/content_security_policy.d.ts +54 -0
  44. package/dist/middleware/cors.d.ts +5 -0
  45. package/dist/middleware/csrf.d.ts +7 -0
  46. package/dist/middleware/ddos_protection.d.ts +47 -0
  47. package/dist/middleware/file_security.d.ts +23 -0
  48. package/dist/middleware/file_upload.d.ts +41 -0
  49. package/dist/middleware/helmet.d.ts +54 -0
  50. package/dist/middleware/index.d.ts +55 -0
  51. package/dist/middleware/input_validation.d.ts +46 -0
  52. package/dist/middleware/json_body.d.ts +4 -0
  53. package/dist/middleware/performance_alerting.d.ts +88 -0
  54. package/dist/middleware/performance_dashboard.d.ts +97 -0
  55. package/dist/middleware/performance_monitor.d.ts +236 -0
  56. package/dist/middleware/pipeline.d.ts +90 -0
  57. package/dist/middleware/rate_limit.d.ts +33 -0
  58. package/dist/middleware/request_id.d.ts +4 -0
  59. package/dist/middleware/request_signing.d.ts +96 -0
  60. package/dist/middleware/request_tracer.d.ts +76 -0
  61. package/dist/middleware/response_cache.d.ts +90 -0
  62. package/dist/middleware/security.d.ts +70 -0
  63. package/dist/middleware/security_suite.d.ts +46 -0
  64. package/dist/middleware/session.d.ts +7 -0
  65. package/dist/model-binding/index.d.ts +17 -0
  66. package/dist/model-binding/model-middleware.d.ts +80 -0
  67. package/dist/model-binding/model-registry.d.ts +125 -0
  68. package/dist/model-binding.d.ts +123 -0
  69. package/dist/model-resolver-factory.d.ts +31 -0
  70. package/dist/observability/correlation.d.ts +131 -0
  71. package/dist/observability/health-checks.d.ts +129 -0
  72. package/dist/observability/index.d.ts +92 -0
  73. package/dist/observability/integration.d.ts +112 -0
  74. package/dist/observability/metrics.d.ts +135 -0
  75. package/dist/observability/tracing.d.ts +112 -0
  76. package/dist/optimization/bun-utilities.d.ts +106 -0
  77. package/dist/query-builder-integration.d.ts +24 -0
  78. package/dist/request/enhanced-request.d.ts +143 -0
  79. package/dist/request/macros.d.ts +267 -0
  80. package/dist/response/macros.d.ts +207 -0
  81. package/dist/response/response-factory.d.ts +93 -0
  82. package/dist/router/file-based-routing.d.ts +40 -0
  83. package/dist/router/file-streaming.d.ts +6 -0
  84. package/dist/router/fluent-router.d.ts +179 -0
  85. package/dist/router/fluent-routing.d.ts +198 -0
  86. package/dist/router/group-organization.d.ts +5 -0
  87. package/dist/router/handler-resolver.d.ts +13 -0
  88. package/dist/router/http-methods.d.ts +10 -0
  89. package/dist/router/index.d.ts +114 -0
  90. package/dist/router/middleware-integration.d.ts +86 -0
  91. package/dist/router/middleware.d.ts +5 -0
  92. package/dist/router/model-binding.d.ts +7 -0
  93. package/dist/router/optimized-route-matching.d.ts +6 -0
  94. package/dist/router/route-building.d.ts +5 -0
  95. package/dist/router/route-compiler.d.ts +67 -0
  96. package/dist/router/route-matching.d.ts +5 -0
  97. package/dist/router/route-trie.d.ts +69 -0
  98. package/dist/router/router.d.ts +133 -0
  99. package/dist/router/server.d.ts +5 -0
  100. package/dist/router/validation-integration.d.ts +116 -0
  101. package/dist/router/view-rendering.d.ts +5 -0
  102. package/dist/router/websocket.d.ts +5 -0
  103. package/dist/routing/route-caching.d.ts +105 -0
  104. package/dist/routing/route-throttling.d.ts +112 -0
  105. package/dist/routing/subdomain-routing.d.ts +159 -0
  106. package/dist/streaming/index.d.ts +15 -0
  107. package/dist/streaming/sse-handler.d.ts +81 -0
  108. package/dist/streaming/stream-handler.d.ts +81 -0
  109. package/dist/testing/auth-testing.d.ts +107 -0
  110. package/dist/testing/file-upload-testing.d.ts +139 -0
  111. package/dist/testing/index.d.ts +10 -0
  112. package/dist/testing/middleware-testing.d.ts +99 -0
  113. package/dist/testing/model-binding-testing.d.ts +132 -0
  114. package/dist/testing/performance-testing.d.ts +202 -0
  115. package/dist/testing/test-client.d.ts +58 -0
  116. package/dist/testing/test-request.d.ts +43 -0
  117. package/dist/testing/test-response.d.ts +45 -0
  118. package/dist/testing/types.d.ts +206 -0
  119. package/dist/testing/websocket-testing.d.ts +170 -0
  120. package/dist/types/controller-types.d.ts +303 -0
  121. package/dist/types/core.d.ts +526 -0
  122. package/dist/types/middleware-types.d.ts +315 -0
  123. package/dist/types/request-response-augmentation.d.ts +373 -0
  124. package/dist/types/route-inference.d.ts +287 -0
  125. package/dist/types.d.ts +1620 -0
  126. package/dist/utils/index.d.ts +1 -0
  127. package/dist/utils/query-preservation.d.ts +31 -0
  128. package/dist/utils.d.ts +69 -0
  129. package/dist/validation/validator.d.ts +169 -0
  130. package/dist/websocket/clustering.d.ts +114 -0
  131. package/package.json +81 -0
@@ -0,0 +1,102 @@
1
+ import type { EnhancedRequest } from '../types';
2
+ /**
3
+ * Initialize global route debugger
4
+ */
5
+ export declare function initializeRouteDebugger(config?: RouteDebugConfig): RouteDebugger;
6
+ /**
7
+ * Get global route debugger
8
+ */
9
+ export declare function getRouteDebugger(): RouteDebugger | null;
10
+ /**
11
+ * Route debugging middleware factory
12
+ */
13
+ export declare function createRouteDebugMiddleware(config?: RouteDebugConfig): void;
14
+ /**
15
+ * Route debugging helpers
16
+ */
17
+ export declare const RouteDebugHelpers: {
18
+ /**
19
+ * Record route match attempt from request context
20
+ */
21
+ recordMatch: (req: EnhancedRequest, pattern: string, method: string, matched: boolean, reason?: string, params?: Record<string, string>) => any;
22
+ /**
23
+ * Record final match from request context
24
+ */
25
+ recordFinalMatch: (req: EnhancedRequest, pattern: string, handler: (...args: any[]) => any, middleware: ((...args: any[]) => any)[], params: Record<string, string>) => any;
26
+ /**
27
+ * Record timing from request context
28
+ */
29
+ recordTiming: (req: EnhancedRequest, phase: keyof RouteDebugInfo['timings'], duration: number) => any
30
+ };
31
+ export declare interface RouteDebugConfig {
32
+ enabled?: boolean
33
+ logLevel?: 'debug' | 'info' | 'warn' | 'error'
34
+ includeHeaders?: boolean
35
+ includeBody?: boolean
36
+ includeParams?: boolean
37
+ includeQuery?: boolean
38
+ includeTimings?: boolean
39
+ maxBodySize?: number
40
+ colorOutput?: boolean
41
+ outputFormat?: 'console' | 'json' | 'structured'
42
+ }
43
+ export declare interface RouteMatchAttempt {
44
+ pattern: string
45
+ method: string
46
+ matched: boolean
47
+ reason?: string
48
+ params?: Record<string, string>
49
+ score?: number
50
+ timing: number
51
+ }
52
+ export declare interface RouteDebugInfo {
53
+ requestId: string
54
+ timestamp: number
55
+ method: string
56
+ url: string
57
+ path: string
58
+ headers?: Record<string, string>
59
+ query?: Record<string, string>
60
+ params?: Record<string, string>
61
+ body?: any
62
+ matchAttempts: RouteMatchAttempt[]
63
+ finalMatch?: {
64
+ pattern: string
65
+ handler: string
66
+ middleware: string[]
67
+ params: Record<string, string>
68
+ }
69
+ timings: {
70
+ routeMatching: number
71
+ middlewareExecution: number
72
+ handlerExecution: number
73
+ total: number
74
+ }
75
+ performance: {
76
+ memoryUsage: NodeJS.MemoryUsage
77
+ cpuTime: number
78
+ }
79
+ }
80
+ /**
81
+ * Route debugger for development
82
+ */
83
+ export declare class RouteDebugger {
84
+ private config: RouteDebugConfig;
85
+ private debugSessions: any;
86
+ private routePatterns: any;
87
+ constructor(config?: RouteDebugConfig);
88
+ startDebugging(req: EnhancedRequest): string;
89
+ recordMatchAttempt(requestId: string, pattern: string, method: string, matched: boolean, reason?: string, params?: Record<string, string>): void;
90
+ recordFinalMatch(requestId: string, pattern: string, handler: (...args: any[]) => any, middleware: ((...args: any[]) => any)[], params: Record<string, string>): void;
91
+ recordTiming(requestId: string, phase: keyof RouteDebugInfo['timings'], duration: number): void;
92
+ finishDebugging(requestId: string, response?: Response): RouteDebugInfo | null;
93
+ registerRoute(method: string, pattern: string, handler: (...args: any[]) => any, middleware?: ((...args: any[]) => any)[]): void;
94
+ getRegisteredRoutes(): Array<{ method: string, pattern: string, handler: string, middleware: string[] }>;
95
+ getDebugSession(requestId: string): RouteDebugInfo | undefined;
96
+ clearSessions(): void;
97
+ private generateRequestId(): string;
98
+ private captureRequestBody(req: EnhancedRequest, debugInfo: RouteDebugInfo): Promise<void>;
99
+ private log(level: string, message: string, data?: any): void;
100
+ private logSummary(debugInfo: RouteDebugInfo, response?: Response): void;
101
+ private shouldLog(level: string): boolean;
102
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Initialize global route inspector
3
+ */
4
+ export declare function initializeRouteInspector(): RouteInspector;
5
+ /**
6
+ * Get global route inspector
7
+ */
8
+ export declare function getRouteInspector(): RouteInspector | null;
9
+ /**
10
+ * Route inspection helpers
11
+ */
12
+ export declare const RouteInspectionHelpers: {
13
+ /**
14
+ * List all routes in a formatted table
15
+ */
16
+ listRoutes: (filter?: Parameters<RouteInspector['getRoutes']>[0]) => any;
17
+ /**
18
+ * Analyze routes and show recommendations
19
+ */
20
+ analyzeRoutes: () => any;
21
+ /**
22
+ * Export routes to file
23
+ */
24
+ exportRoutes: (format: 'json' | 'csv' | 'markdown' | 'openapi' = 'json', filename?: string) => any
25
+ };
26
+ /**
27
+ * Development Tools - Route Inspector
28
+ *
29
+ * Route listing, metadata inspection, and route analysis
30
+ */
31
+ export declare interface RouteMetadata {
32
+ id: string
33
+ method: string
34
+ pattern: string
35
+ originalPattern: string
36
+ handler: {
37
+ name: string
38
+ source?: string
39
+ parameters: string[]
40
+ isAsync: boolean
41
+ }
42
+ middleware: Array<{
43
+ name: string
44
+ source?: string
45
+ order: number
46
+ }>
47
+ params: Array<{
48
+ name: string
49
+ type: 'string' | 'number' | 'uuid' | 'slug'
50
+ optional: boolean
51
+ constraint?: string
52
+ }>
53
+ constraints: Record<string, any>
54
+ cache?: {
55
+ enabled: boolean
56
+ ttl?: number
57
+ tags?: string[]
58
+ }
59
+ throttling?: {
60
+ enabled: boolean
61
+ limit: number
62
+ window: number
63
+ }
64
+ validation?: {
65
+ rules: Record<string, string>
66
+ messages?: Record<string, string>
67
+ }
68
+ metadata: {
69
+ registeredAt: number
70
+ file?: string
71
+ line?: number
72
+ group?: string
73
+ name?: string
74
+ description?: string
75
+ }
76
+ stats: {
77
+ hits: number
78
+ averageResponseTime: number
79
+ lastAccessed?: number
80
+ errors: number
81
+ }
82
+ }
83
+ export declare interface RouteGroup {
84
+ name: string
85
+ prefix: string
86
+ middleware: string[]
87
+ routes: RouteMetadata[]
88
+ subgroups: RouteGroup[]
89
+ }
90
+ export declare interface RouteAnalysis {
91
+ totalRoutes: number
92
+ routesByMethod: Record<string, number>
93
+ duplicatePatterns: Array<{
94
+ pattern: string
95
+ routes: RouteMetadata[]
96
+ }>
97
+ unusedRoutes: RouteMetadata[]
98
+ slowRoutes: RouteMetadata[]
99
+ errorProneRoutes: RouteMetadata[]
100
+ middlewareUsage: Record<string, number>
101
+ parameterAnalysis: {
102
+ mostUsedParams: Array<{ name: string, count: number }>
103
+ parameterTypes: Record<string, number>
104
+ }
105
+ recommendations: string[]
106
+ }
107
+ /**
108
+ * Route inspector for development and debugging
109
+ */
110
+ export declare class RouteInspector {
111
+ private routes: any;
112
+ private groups: any;
113
+ private routeStats: any;
114
+ registerRoute(method: string, pattern: string, handler: (...args: any[]) => any, middleware?: Array<(...args: any[]) => any>, options?: Partial<RouteMetadata>): string;
115
+ getRoutes(filter?: {
116
+ method?: string
117
+ pattern?: string
118
+ group?: string
119
+ hasMiddleware?: string
120
+ hasParams?: boolean
121
+ }): RouteMetadata[];
122
+ getRoute(id: string): RouteMetadata | undefined;
123
+ findMatchingRoutes(method: string, path: string): RouteMetadata[];
124
+ registerGroup(name: string, prefix: string, middleware?: Array<(...args: any[]) => any>): void;
125
+ getGroups(): RouteGroup[];
126
+ recordRouteAccess(routeId: string, responseTime: number, error?: boolean): void;
127
+ analyzeRoutes(): RouteAnalysis;
128
+ exportRoutes(format?: 'json' | 'csv' | 'markdown' | 'openapi'): string;
129
+ clear(): void;
130
+ private generateRouteId(method: string, pattern: string): string;
131
+ private getFunctionSource(fn: (...args: any[]) => any): string | undefined;
132
+ private extractFunctionParameters(fn: (...args: any[]) => any): string[];
133
+ private isAsyncFunction(fn: (...args: any[]) => any): boolean;
134
+ private extractRouteParameters(pattern: string): RouteMetadata['params'];
135
+ private inferParameterType(constraint?: string): 'string' | 'number' | 'uuid' | 'slug';
136
+ private getCallSiteInfo(): { file?: string, line?: number };
137
+ private patternToRegex(pattern: string): RegExp;
138
+ private generateRecommendations(analysis: RouteAnalysis): string[];
139
+ private exportToCsv(routes: RouteMetadata[]): string;
140
+ private exportToMarkdown(routes: RouteMetadata[]): string;
141
+ private exportToOpenAPI(routes: RouteMetadata[]): string;
142
+ }
@@ -0,0 +1,116 @@
1
+ import type { EnhancedRequest } from '../types';
2
+ /**
3
+ * Initialize global TypeScript utilities
4
+ */
5
+ export declare function initializeTypeScriptUtilities(config?: TypeScriptConfig): TypeScriptUtilities;
6
+ /**
7
+ * Get global TypeScript utilities
8
+ */
9
+ export declare function getTypeScriptUtilities(): TypeScriptUtilities | null;
10
+ /**
11
+ * TypeScript development helpers
12
+ */
13
+ export declare const TypeScriptHelpers: {
14
+ /**
15
+ * Generate types for current routes
16
+ */
17
+ generateTypes: () => any;
18
+ /**
19
+ * Generate validation schemas
20
+ */
21
+ generateSchemas: () => unknown;
22
+ /**
23
+ * Generate OpenAPI documentation
24
+ */
25
+ generateOpenAPI: () => any;
26
+ /**
27
+ * Validate request types
28
+ */
29
+ validateRequest: (req: EnhancedRequest, routeKey: string) => unknown
30
+ };
31
+ export declare interface TypeScriptConfig {
32
+ strictMode?: boolean
33
+ generateTypes?: boolean
34
+ validateTypes?: boolean
35
+ outputDir?: string
36
+ includeComments?: boolean
37
+ generateSchemas?: boolean
38
+ }
39
+ export declare interface RouteTypeInfo {
40
+ method: string
41
+ pattern: string
42
+ requestType: string
43
+ responseType: string
44
+ paramsType: string
45
+ queryType: string
46
+ bodyType: string
47
+ middlewareTypes: string[]
48
+ handlerSignature: string
49
+ }
50
+ export declare interface TypeDefinition {
51
+ name: string
52
+ type: 'interface' | 'type' | 'enum' | 'class'
53
+ definition: string
54
+ imports: string[]
55
+ exports: string[]
56
+ documentation?: string
57
+ }
58
+ export declare interface ValidationSchema {
59
+ type: 'object' | 'array' | 'string' | 'number' | 'boolean'
60
+ properties?: Record<string, ValidationSchema>
61
+ items?: ValidationSchema
62
+ required?: string[]
63
+ pattern?: string
64
+ minimum?: number
65
+ maximum?: number
66
+ enum?: any[]
67
+ }
68
+ /**
69
+ * TypeScript utilities for development
70
+ */
71
+ export declare class TypeScriptUtilities {
72
+ private config: TypeScriptConfig;
73
+ private routeTypes: any;
74
+ private typeDefinitions: any;
75
+ constructor(config?: TypeScriptConfig);
76
+ registerRouteTypes(method: string, pattern: string, options?: {
77
+ requestType?: string
78
+ responseType?: string
79
+ paramsType?: string
80
+ queryType?: string
81
+ bodyType?: string
82
+ middlewareTypes?: string[]
83
+ handlerSignature?: string
84
+ }): void;
85
+ generateRouteTypes(): string;
86
+ generateValidationSchemas(): Record<string, ValidationSchema>;
87
+ generateOpenAPISchema(): any;
88
+ validateRequest(req: EnhancedRequest, routeKey: string): {
89
+ valid: boolean
90
+ errors: string[]
91
+ warnings: string[]
92
+ };
93
+ generateRouteBuilder(): string;
94
+ generateMiddlewareTypes(): string;
95
+ getRouteTypes(): RouteTypeInfo[];
96
+ getTypeDefinition(name: string): TypeDefinition | undefined;
97
+ registerTypeDefinition(definition: TypeDefinition): void;
98
+ clear(): void;
99
+ private inferParamsType(pattern: string): string;
100
+ private extractPathParameters(pattern: string): Array<{ name: string, type: string, optional: boolean }>;
101
+ private inferParamType(constraint?: string): string;
102
+ private generateHandlerSignature(options: any): string;
103
+ private generateImports(): string;
104
+ private generateParamTypes(routes: RouteTypeInfo[]): string;
105
+ private generateHandlerTypes(routes: RouteTypeInfo[]): string;
106
+ private generateRouteRegistryType(routes: RouteTypeInfo[]): string;
107
+ private generateUtilityTypes(): string;
108
+ private pathToTypeName(path: string): string;
109
+ private pathToMethodName(path: string): string;
110
+ private pathToOperationId(path: string): string;
111
+ private typeToSchema(type: string): ValidationSchema;
112
+ private typeToOpenAPISchema(type: string): any;
113
+ private validateParams(_req: EnhancedRequest, _expectedType: string): string[];
114
+ private validateQuery(_req: EnhancedRequest, _expectedType: string): string[];
115
+ private validateBody(_req: EnhancedRequest, _expectedType: string): string[];
116
+ }
package/dist/docs.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Generates API documentation from route definitions
3
+ */
4
+ export declare function generateApiDocs(options?: DocsOptions): Promise<void>;
5
+ declare interface DocsOptions {
6
+ verbose?: boolean
7
+ output?: string
8
+ groupBy?: 'path' | 'method' | 'tag'
9
+ includeExamples?: boolean
10
+ }
@@ -0,0 +1,138 @@
1
+ import type { ErrorContext } from './exceptions';
2
+ /**
3
+ * Decorator for circuit breaker protection
4
+ */
5
+ export declare function circuitBreaker(config: CircuitBreakerConfig): <T extends (...args: any[]) => Promise<any>>(
6
+ target: any,
7
+ propertyName: string,
8
+ descriptor: TypedPropertyDescriptor<T>,
9
+ ) => TypedPropertyDescriptor<T>;
10
+ /**
11
+ * Middleware for circuit breaker protection
12
+ */
13
+ export declare function createCircuitBreakerMiddleware(registry: CircuitBreakerRegistry): void;
14
+ /**
15
+ * Convenience function to create and register a circuit breaker
16
+ */
17
+ export declare function createCircuitBreaker(config: CircuitBreakerConfig): CircuitBreaker;
18
+ /**
19
+ * Convenience function to execute with circuit breaker protection
20
+ */
21
+ export declare function withCircuitBreaker<T>(name: string, call: CircuitBreakerCall<T>): Promise<T>;
22
+ /**
23
+ * Factory functions for common circuit breaker configurations
24
+ */
25
+ export declare const CircuitBreakerPresets: {
26
+ /**
27
+ * Fast-failing circuit breaker for critical services
28
+ */
29
+ critical: (name: string) => any;
30
+ /**
31
+ * Standard circuit breaker for regular services
32
+ */
33
+ standard: (name: string) => any;
34
+ /**
35
+ * Tolerant circuit breaker for non-critical services
36
+ */
37
+ tolerant: (name: string) => any;
38
+ /**
39
+ * Database circuit breaker with longer timeouts
40
+ */
41
+ database: (name: string) => any
42
+ };
43
+ /**
44
+ * Global circuit breaker registry instance
45
+ */
46
+ export declare const globalCircuitBreakerRegistry: CircuitBreakerRegistry;
47
+ export declare interface CircuitBreakerConfig {
48
+ name: string
49
+ failureThreshold: number
50
+ recoveryTimeout: number
51
+ timeout: number
52
+ monitoringPeriod: number
53
+ minimumRequests: number
54
+ errorThresholdPercentage: number
55
+ halfOpenMaxCalls: number
56
+ resetTimeout: number
57
+ onStateChange?: (state: CircuitBreakerState, name: string) => void
58
+ onFailure?: (error: Error, name: string) => void
59
+ onSuccess?: (name: string) => void
60
+ shouldTripOnError?: (error: Error) => boolean
61
+ }
62
+ export declare interface CircuitBreakerMetrics {
63
+ totalRequests: number
64
+ successfulRequests: number
65
+ failedRequests: number
66
+ timeouts: number
67
+ averageResponseTime: number
68
+ lastFailureTime?: Date
69
+ lastSuccessTime?: Date
70
+ state: CircuitBreakerState
71
+ nextAttemptTime?: Date
72
+ consecutiveFailures: number
73
+ consecutiveSuccesses: number
74
+ }
75
+ export declare interface CircuitBreakerCall<T> {
76
+ execute: () => Promise<T>
77
+ fallback?: () => Promise<T>
78
+ timeout?: number
79
+ retries?: number
80
+ context?: ErrorContext
81
+ }
82
+ export type CircuitBreakerState = 'CLOSED' | 'OPEN' | 'HALF_OPEN'
83
+ /**
84
+ * Circuit breaker implementation
85
+ */
86
+ export declare class CircuitBreaker {
87
+ private config: CircuitBreakerConfig;
88
+ private state: CircuitBreakerState;
89
+ private metrics: CircuitBreakerMetrics;
90
+ private nextAttemptTime?: Date;
91
+ private halfOpenCallCount: any;
92
+ private recentRequests: Array<{ timestamp: Date, success: boolean, responseTime: number }>;
93
+ constructor(config: CircuitBreakerConfig);
94
+ execute<T>(call: CircuitBreakerCall<T>): Promise<T>;
95
+ getState(): CircuitBreakerState;
96
+ getMetrics(): CircuitBreakerMetrics;
97
+ forceOpen(): void;
98
+ forceClosed(): void;
99
+ reset(): void;
100
+ private onSuccess(responseTime: number): void;
101
+ private onFailure(error: Error, responseTime: number): void;
102
+ private shouldTrip(error: Error): boolean;
103
+ private transitionToClosed(): void;
104
+ private transitionToOpen(): void;
105
+ private transitionToHalfOpen(): void;
106
+ private updateAverageResponseTime(responseTime: number): void;
107
+ private getRecentRequests(): Array<{ timestamp: Date, success: boolean, responseTime: number }>;
108
+ private cleanupOldRequests(): void;
109
+ }
110
+ /**
111
+ * Circuit breaker registry for managing multiple circuit breakers
112
+ */
113
+ export declare class CircuitBreakerRegistry {
114
+ private breakers: any;
115
+ private configs: any;
116
+ register(config: CircuitBreakerConfig): CircuitBreaker;
117
+ get(name: string): CircuitBreaker | undefined;
118
+ execute<T>(name: string, call: CircuitBreakerCall<T>): Promise<T>;
119
+ getAllMetrics(): Record<string, CircuitBreakerMetrics>;
120
+ getBreakersByState(state: CircuitBreakerState): string[];
121
+ forceAllClosed(): void;
122
+ resetAll(): void;
123
+ remove(name: string): boolean;
124
+ getNames(): string[];
125
+ }
126
+ /**
127
+ * HTTP client with circuit breaker protection
128
+ */
129
+ export declare class CircuitBreakerHttpClient {
130
+ private registry: CircuitBreakerRegistry;
131
+ constructor(registry?: CircuitBreakerRegistry);
132
+ fetch(url: string, options?: RequestInit & {
133
+ circuitBreaker?: string | CircuitBreakerConfig
134
+ fallback?: () => Promise<Response>
135
+ context?: ErrorContext
136
+ }): Promise<Response>;
137
+ getRegistry(): CircuitBreakerRegistry;
138
+ }
@@ -0,0 +1,57 @@
1
+ import { CircuitBreakerRegistry } from './circuit-breaker';
2
+ import { ErrorReportingManager } from './error-reporting';
3
+ import { GracefulDegradationManager } from './graceful-degradation';
4
+ import { RouterException } from './exceptions';
5
+ import type { CircuitBreakerConfig, DegradationConfig, EnhancedRequest, ErrorReportingConfig } from '../types';
6
+ /**
7
+ * Factory function to create advanced error handler middleware
8
+ */
9
+ export declare function createAdvancedErrorHandler(config?: AdvancedErrorHandlerConfig): {
10
+ middleware: (req: EnhancedRequest, next: () => Promise<Response>) => Promise<Response>
11
+ getStats: () => { errorReporting?: any, gracefulDegradation?: any, circuitBreakers?: any }
12
+ cleanup: () => Promise<void>
13
+ };
14
+ /**
15
+ * Preset configurations for different environments
16
+ */
17
+ export declare const ErrorHandlerPresets: {
18
+ development: () => any;
19
+ production: (sentryDsn?: string, bugsnagApiKey?: string) => any;
20
+ staging: (sentryDsn?: string) => any;
21
+ resilient: (config: { sentryDsn?: string bugsnagApiKey?: string services?: string[] } = {}) => any
22
+ };
23
+ export declare interface AdvancedErrorHandlerConfig {
24
+ errorReporting?: ErrorReportingConfig[]
25
+ gracefulDegradation?: DegradationConfig
26
+ circuitBreakers?: CircuitBreakerConfig[]
27
+ globalErrorHandler?: (error: RouterException, req: EnhancedRequest) => Promise<Response>
28
+ development?: boolean
29
+ includeStackTrace?: boolean
30
+ sanitizeErrors?: boolean
31
+ logErrors?: boolean
32
+ customErrorPages?: {
33
+ [statusCode: number]: string | ((error: RouterException, req: EnhancedRequest) => Promise<Response>)
34
+ }
35
+ }
36
+ /**
37
+ * Advanced error handler middleware
38
+ */
39
+ export declare class AdvancedErrorHandler {
40
+ private errorReporting?: ErrorReportingManager;
41
+ private gracefulDegradation?: GracefulDegradationManager;
42
+ private circuitBreakerRegistry?: CircuitBreakerRegistry;
43
+ private config: AdvancedErrorHandlerConfig;
44
+ constructor(config?: AdvancedErrorHandlerConfig);
45
+ private initializeComponents(): void;
46
+ middleware(): void;
47
+ handleError(error: unknown, req: EnhancedRequest): Promise<Response>;
48
+ private normalizeError(error: unknown, req: EnhancedRequest): RouterException;
49
+ private createErrorResponse(error: RouterException, _req: EnhancedRequest): Response;
50
+ private logError(error: RouterException, req: EnhancedRequest): void;
51
+ getStats(): {
52
+ errorReporting?: any
53
+ gracefulDegradation?: any
54
+ circuitBreakers?: any
55
+ };
56
+ cleanup(): Promise<void>;
57
+ }