@stacksjs/bun-router 0.0.4 → 0.0.6

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 (272) hide show
  1. package/README.md +2 -2
  2. package/dist/auth.d.ts +134 -0
  3. package/dist/cache/lru-cache.d.ts +139 -0
  4. package/dist/cache/middleware-memoization.d.ts +151 -0
  5. package/dist/cache/route-cache-warmer.d.ts +161 -0
  6. package/dist/cache/sqlite-cache.d.ts +209 -0
  7. package/dist/cache/streaming-cache.d.ts +132 -0
  8. package/dist/chunk-jhsk5c5b.js +15758 -0
  9. package/dist/cli/colors.d.ts +15 -0
  10. package/dist/cli/index.d.ts +10 -0
  11. package/dist/cli/middleware.d.ts +31 -0
  12. package/dist/cli/openapi.d.ts +17 -0
  13. package/dist/cli/router.d.ts +15 -0
  14. package/dist/cli/routes.d.ts +29 -0
  15. package/dist/cli/utils.d.ts +74 -0
  16. package/dist/cli.d.ts +1 -1
  17. package/dist/cli.js +2 -2
  18. package/dist/config.d.ts +7 -0
  19. package/dist/container/container.d.ts +273 -0
  20. package/dist/container/contextual-binding.d.ts +240 -0
  21. package/dist/container/decorators.d.ts +141 -0
  22. package/dist/container/service-provider.d.ts +285 -0
  23. package/dist/development/hot-reload.d.ts +187 -0
  24. package/dist/development/index.d.ts +167 -0
  25. package/dist/development/performance-profiler.d.ts +217 -0
  26. package/dist/development/route-debugger.d.ts +154 -0
  27. package/dist/development/route-inspector.d.ts +211 -0
  28. package/dist/development/typescript-utilities.d.ts +209 -0
  29. package/dist/docs.d.ts +11 -0
  30. package/dist/errors/circuit-breaker.d.ts +195 -0
  31. package/dist/errors/error-handler.d.ts +88 -0
  32. package/dist/errors/error-reporting.d.ts +144 -0
  33. package/dist/errors/exceptions.d.ts +184 -0
  34. package/dist/errors/graceful-degradation.d.ts +154 -0
  35. package/dist/errors/index.d.ts +9 -0
  36. package/dist/errors/router-errors.d.ts +110 -0
  37. package/dist/file-serving/static-files.d.ts +143 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +320 -206
  40. package/dist/middleware/auth.d.ts +63 -0
  41. package/dist/middleware/content_security_policy.d.ts +53 -0
  42. package/dist/middleware/cors.d.ts +5 -0
  43. package/dist/middleware/csrf.d.ts +7 -0
  44. package/dist/middleware/ddos_protection.d.ts +39 -0
  45. package/dist/middleware/file_security.d.ts +26 -0
  46. package/dist/middleware/file_upload.d.ts +38 -0
  47. package/dist/middleware/helmet.d.ts +54 -0
  48. package/dist/middleware/index.d.ts +44 -0
  49. package/dist/middleware/input_validation.d.ts +45 -0
  50. package/dist/middleware/json_body.d.ts +4 -0
  51. package/dist/middleware/performance_alerting.d.ts +87 -0
  52. package/dist/middleware/performance_dashboard.d.ts +87 -0
  53. package/dist/middleware/performance_monitor.d.ts +209 -0
  54. package/dist/middleware/pipeline.d.ts +131 -0
  55. package/dist/middleware/rate_limit.d.ts +36 -0
  56. package/dist/middleware/request_id.d.ts +4 -0
  57. package/dist/middleware/request_signing.d.ts +153 -0
  58. package/dist/middleware/request_tracer.d.ts +72 -0
  59. package/dist/middleware/response_cache.d.ts +97 -0
  60. package/dist/middleware/security.d.ts +69 -0
  61. package/dist/middleware/security_suite.d.ts +46 -0
  62. package/dist/middleware/session.d.ts +23 -0
  63. package/dist/model-binding/index.d.ts +2 -0
  64. package/dist/model-binding/model-middleware.d.ts +118 -0
  65. package/dist/model-binding/model-registry.d.ts +164 -0
  66. package/dist/model-binding.d.ts +185 -0
  67. package/dist/model-resolver-factory.d.ts +31 -0
  68. package/dist/observability/correlation.d.ts +187 -0
  69. package/dist/observability/health-checks.d.ts +186 -0
  70. package/dist/observability/index.d.ts +60 -0
  71. package/dist/observability/integration.d.ts +147 -0
  72. package/dist/observability/metrics.d.ts +184 -0
  73. package/dist/observability/tracing.d.ts +187 -0
  74. package/dist/optimization/bun-utilities.d.ts +224 -0
  75. package/dist/query-builder-integration.d.ts +36 -0
  76. package/dist/request/context.d.ts +34 -0
  77. package/dist/request/enhanced-request.d.ts +213 -0
  78. package/dist/request/macros.d.ts +300 -0
  79. package/dist/response/macros.d.ts +245 -0
  80. package/dist/response/response-factory.d.ts +133 -0
  81. package/dist/router/api-routes.d.ts +5 -0
  82. package/dist/router/file-based-routing.d.ts +118 -0
  83. package/dist/router/file-streaming.d.ts +5 -0
  84. package/dist/router/fluent-router.d.ts +315 -0
  85. package/dist/router/fluent-routing.d.ts +271 -0
  86. package/dist/router/group-organization.d.ts +5 -0
  87. package/dist/router/handler-resolver.d.ts +24 -0
  88. package/dist/router/http-methods.d.ts +10 -0
  89. package/dist/router/index.d.ts +113 -0
  90. package/dist/router/middleware-groups.d.ts +94 -0
  91. package/dist/router/middleware-integration.d.ts +112 -0
  92. package/dist/router/middleware.d.ts +5 -0
  93. package/dist/router/model-binding.d.ts +5 -0
  94. package/dist/router/optimized-route-matching.d.ts +6 -0
  95. package/dist/router/route-building.d.ts +5 -0
  96. package/dist/router/route-compiler.d.ts +153 -0
  97. package/dist/router/route-matching.d.ts +5 -0
  98. package/dist/router/route-trie.d.ts +114 -0
  99. package/dist/router/router.d.ts +276 -0
  100. package/dist/router/server.d.ts +5 -0
  101. package/dist/router/validation-integration.d.ts +170 -0
  102. package/dist/router/view-rendering.d.ts +5 -0
  103. package/dist/router/websocket.d.ts +5 -0
  104. package/dist/routing/route-caching.d.ts +129 -0
  105. package/dist/routing/route-throttling.d.ts +150 -0
  106. package/dist/routing/subdomain-routing.d.ts +206 -0
  107. package/dist/session/database-store.d.ts +51 -0
  108. package/dist/session/file-store.d.ts +22 -0
  109. package/dist/session/index.d.ts +106 -0
  110. package/dist/session/memory-store.d.ts +21 -0
  111. package/dist/session/redis-store.d.ts +31 -0
  112. package/dist/streaming/index.d.ts +3 -0
  113. package/dist/streaming/sse-handler.d.ts +138 -0
  114. package/dist/streaming/stream-handler.d.ts +114 -0
  115. package/dist/testing/auth-testing.d.ts +156 -0
  116. package/dist/testing/file-upload-testing.d.ts +190 -0
  117. package/dist/testing/index.d.ts +10 -0
  118. package/dist/testing/middleware-testing.d.ts +138 -0
  119. package/dist/testing/model-binding-testing.d.ts +186 -0
  120. package/dist/testing/performance-testing.d.ts +235 -0
  121. package/dist/testing/test-client.d.ts +117 -0
  122. package/dist/testing/test-request.d.ts +85 -0
  123. package/dist/testing/test-response.d.ts +90 -0
  124. package/dist/testing/types.d.ts +207 -0
  125. package/dist/testing/websocket-testing.d.ts +227 -0
  126. package/dist/types/controller-types.d.ts +208 -0
  127. package/dist/types/core.d.ts +543 -0
  128. package/dist/types/middleware-types.d.ts +227 -0
  129. package/dist/types/request-response-augmentation.d.ts +261 -0
  130. package/dist/types/route-inference.d.ts +168 -0
  131. package/dist/types.d.ts +1776 -0
  132. package/dist/url.d.ts +56 -0
  133. package/dist/utils/index.d.ts +1 -0
  134. package/dist/utils/query-preservation.d.ts +48 -0
  135. package/dist/utils.d.ts +69 -0
  136. package/dist/validation/validator.d.ts +140 -0
  137. package/dist/websocket/clustering.d.ts +185 -0
  138. package/package.json +18 -4
  139. package/src/auth.ts +469 -0
  140. package/src/cache/lru-cache.ts +457 -0
  141. package/src/cache/middleware-memoization.ts +531 -0
  142. package/src/cache/route-cache-warmer.ts +486 -0
  143. package/src/cache/sqlite-cache.ts +783 -0
  144. package/src/cache/streaming-cache.ts +572 -0
  145. package/src/cli/colors.ts +29 -0
  146. package/src/cli/index.ts +287 -0
  147. package/src/cli/middleware.ts +291 -0
  148. package/src/cli/openapi.ts +407 -0
  149. package/src/cli/router.ts +188 -0
  150. package/src/cli/routes.ts +265 -0
  151. package/src/cli/utils.ts +531 -0
  152. package/src/cli.ts +5 -0
  153. package/src/config.ts +322 -0
  154. package/src/container/container.ts +740 -0
  155. package/src/container/contextual-binding.ts +603 -0
  156. package/src/container/decorators.ts +359 -0
  157. package/src/container/service-provider.ts +596 -0
  158. package/src/development/hot-reload.ts +673 -0
  159. package/src/development/index.ts +499 -0
  160. package/src/development/performance-profiler.ts +717 -0
  161. package/src/development/route-debugger.ts +527 -0
  162. package/src/development/route-inspector.ts +749 -0
  163. package/src/development/typescript-utilities.ts +678 -0
  164. package/src/docs.ts +397 -0
  165. package/src/errors/circuit-breaker.ts +732 -0
  166. package/src/errors/error-handler.ts +569 -0
  167. package/src/errors/error-reporting.ts +672 -0
  168. package/src/errors/exceptions.ts +536 -0
  169. package/src/errors/graceful-degradation.ts +621 -0
  170. package/src/errors/index.ts +21 -0
  171. package/src/errors/router-errors.ts +632 -0
  172. package/src/file-serving/static-files.ts +581 -0
  173. package/src/index.ts +14 -0
  174. package/src/middleware/auth.ts +219 -0
  175. package/src/middleware/content_security_policy.ts +215 -0
  176. package/src/middleware/cors.ts +74 -0
  177. package/src/middleware/csrf.ts +108 -0
  178. package/src/middleware/ddos_protection.ts +255 -0
  179. package/src/middleware/file_security.ts +191 -0
  180. package/src/middleware/file_upload.ts +264 -0
  181. package/src/middleware/helmet.ts +268 -0
  182. package/src/middleware/index.ts +117 -0
  183. package/src/middleware/input_validation.ts +449 -0
  184. package/src/middleware/json_body.ts +37 -0
  185. package/src/middleware/performance_alerting.ts +538 -0
  186. package/src/middleware/performance_dashboard.ts +661 -0
  187. package/src/middleware/performance_monitor.ts +943 -0
  188. package/src/middleware/pipeline.ts +489 -0
  189. package/src/middleware/rate_limit.ts +245 -0
  190. package/src/middleware/request_id.ts +36 -0
  191. package/src/middleware/request_signing.ts +636 -0
  192. package/src/middleware/request_tracer.ts +636 -0
  193. package/src/middleware/response_cache.ts +743 -0
  194. package/src/middleware/security.ts +482 -0
  195. package/src/middleware/security_suite.ts +257 -0
  196. package/src/middleware/session.ts +91 -0
  197. package/src/model-binding/index.ts +18 -0
  198. package/src/model-binding/model-middleware.ts +425 -0
  199. package/src/model-binding/model-registry.ts +550 -0
  200. package/src/model-binding.ts +370 -0
  201. package/src/model-resolver-factory.ts +106 -0
  202. package/src/observability/correlation.ts +691 -0
  203. package/src/observability/health-checks.ts +729 -0
  204. package/src/observability/index.ts +184 -0
  205. package/src/observability/integration.ts +548 -0
  206. package/src/observability/metrics.ts +753 -0
  207. package/src/observability/tracing.ts +638 -0
  208. package/src/optimization/bun-utilities.ts +778 -0
  209. package/src/query-builder-integration.ts +137 -0
  210. package/src/request/context.ts +62 -0
  211. package/src/request/enhanced-request.ts +857 -0
  212. package/src/request/macros.ts +688 -0
  213. package/src/response/macros.ts +612 -0
  214. package/src/response/response-factory.ts +588 -0
  215. package/src/router/api-routes.ts +243 -0
  216. package/src/router/file-based-routing.ts +670 -0
  217. package/src/router/file-streaming.ts +372 -0
  218. package/src/router/fluent-router.ts +927 -0
  219. package/src/router/fluent-routing.ts +797 -0
  220. package/src/router/group-organization.ts +213 -0
  221. package/src/router/handler-resolver.ts +291 -0
  222. package/src/router/http-methods.ts +377 -0
  223. package/src/router/index.ts +185 -0
  224. package/src/router/middleware-groups.ts +222 -0
  225. package/src/router/middleware-integration.ts +399 -0
  226. package/src/router/middleware.ts +231 -0
  227. package/src/router/model-binding.ts +215 -0
  228. package/src/router/optimized-route-matching.ts +253 -0
  229. package/src/router/route-building.ts +212 -0
  230. package/src/router/route-compiler.ts +702 -0
  231. package/src/router/route-matching.ts +349 -0
  232. package/src/router/route-trie.ts +464 -0
  233. package/src/router/router.ts +1508 -0
  234. package/src/router/server.ts +406 -0
  235. package/src/router/validation-integration.ts +443 -0
  236. package/src/router/view-rendering.ts +233 -0
  237. package/src/router/websocket.ts +100 -0
  238. package/src/routing/route-caching.ts +402 -0
  239. package/src/routing/route-throttling.ts +469 -0
  240. package/src/routing/subdomain-routing.ts +492 -0
  241. package/src/session/database-store.ts +109 -0
  242. package/src/session/file-store.ts +148 -0
  243. package/src/session/index.ts +244 -0
  244. package/src/session/memory-store.ts +88 -0
  245. package/src/session/redis-store.ts +93 -0
  246. package/src/streaming/index.ts +17 -0
  247. package/src/streaming/sse-handler.ts +482 -0
  248. package/src/streaming/stream-handler.ts +552 -0
  249. package/src/testing/auth-testing.ts +446 -0
  250. package/src/testing/file-upload-testing.ts +543 -0
  251. package/src/testing/index.ts +10 -0
  252. package/src/testing/middleware-testing.ts +322 -0
  253. package/src/testing/model-binding-testing.ts +645 -0
  254. package/src/testing/performance-testing.ts +738 -0
  255. package/src/testing/test-client.ts +310 -0
  256. package/src/testing/test-request.ts +315 -0
  257. package/src/testing/test-response.ts +332 -0
  258. package/src/testing/types.ts +224 -0
  259. package/src/testing/websocket-testing.ts +590 -0
  260. package/src/types/controller-types.ts +385 -0
  261. package/src/types/core.ts +683 -0
  262. package/src/types/middleware-types.ts +419 -0
  263. package/src/types/request-response-augmentation.ts +489 -0
  264. package/src/types/route-inference.ts +357 -0
  265. package/src/types.ts +2049 -0
  266. package/src/url.ts +126 -0
  267. package/src/utils/index.ts +1 -0
  268. package/src/utils/query-preservation.ts +201 -0
  269. package/src/utils.ts +327 -0
  270. package/src/validation/validator.ts +685 -0
  271. package/src/websocket/clustering.ts +762 -0
  272. package/dist/chunk-cjdekj87.js +0 -25886
@@ -0,0 +1,1776 @@
1
+ import type { Server } from 'bun';
2
+ import type { Router } from './router/router';
3
+ import type { QueryPreservationConfig } from './utils/query-preservation';
4
+ import type { AuthContext, AuthenticatedUser, BoundModels, CacheAdapter, CacheStats, CookieToDelete, CookieToSet, ErrorMetadata, FallbackError, FileInfo, FlashMessages, FormBody, InputValidationSchemas, InputValue, JsonBodyData, JwtHeader, JwtPayload, MetricEntry, MiddlewareParams, OAuth2Flows, OAuth2Profile, RequestContext, RequestInput, RouteMetadata, SanitizationOptions, SanitizationRule, SessionData, SessionSerializer, SessionStore, SSEConnection, StaticResponseBody, TemplateHelper, TemplateHelpers, TraceAttributes, TraceSpan, TypedServerWebSocket, User, ValidatedBody, ValidatedData, ValidationSchema, WebSocketData } from './types/core';
5
+ export type { QueryPreservationConfig } from './utils/query-preservation';
6
+ export type { AuthContext, AuthenticatedUser, BoundModels, CacheAdapter, CacheStats, CookieToDelete, CookieToSet, ErrorMetadata, FallbackError, FileInfo, FlashMessages, FormBody, InputValidationSchemas, InputValue, JsonBodyData, JwtHeader, JwtPayload, MetricEntry, MiddlewareParams, OAuth2Flows, OAuth2Profile, RequestContext, RequestInput, RouteMetadata, SanitizationOptions, SanitizationRule, SessionData, SessionSerializer, SessionStore, SSEConnection, StaticResponseBody, TemplateHelper, TemplateHelpers, TraceAttributes, TraceSpan, TypedServerWebSocket, User, ValidatedBody, ValidatedData, ValidationSchema, WebSocketData, };
7
+ export interface Contact {
8
+ name?: string;
9
+ email?: string;
10
+ url?: string;
11
+ }
12
+ export interface SecurityScheme {
13
+ type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect';
14
+ scheme?: string;
15
+ bearerFormat?: string;
16
+ name?: string;
17
+ in?: 'header' | 'query' | 'cookie';
18
+ flows?: OAuth2Flows;
19
+ }
20
+ export interface DocsConfig {
21
+ output: string;
22
+ groupBy: 'path' | 'method' | 'tag';
23
+ includeExamples: boolean;
24
+ title: string;
25
+ description: string;
26
+ version: string;
27
+ baseUrl: string;
28
+ contact?: Contact;
29
+ security?: Record<string, SecurityScheme>;
30
+ }
31
+ export interface CorsConfig {
32
+ enabled?: boolean;
33
+ origin?: string | string[];
34
+ methods?: string[];
35
+ allowedHeaders?: string[];
36
+ exposedHeaders?: string[];
37
+ credentials?: boolean;
38
+ maxAge?: number;
39
+ preflightContinue?: boolean;
40
+ optionsSuccessStatus?: number;
41
+ privateNetworkAccess?: boolean;
42
+ }
43
+ export interface RateLimitConfig {
44
+ enabled?: boolean;
45
+ max?: number;
46
+ timeWindow?: number;
47
+ message?: string;
48
+ draftMode?: boolean;
49
+ advanced?: {
50
+ tokensPerInterval?: number;
51
+ interval?: number;
52
+ burst?: number;
53
+ skipFailedRequests?: boolean;
54
+ keyGenerator?: (req: Request) => string;
55
+ algorithm?: 'fixed-window' | 'sliding-window' | 'token-bucket';
56
+ };
57
+ stores?: {
58
+ type: 'memory' | 'redis';
59
+ redis?: {
60
+ url: string;
61
+ prefix?: string;
62
+ };
63
+ };
64
+ }
65
+ export interface CompressionConfig {
66
+ enabled: boolean;
67
+ level: number;
68
+ threshold: number;
69
+ }
70
+ export interface StaticConfig {
71
+ enabled: boolean;
72
+ dir: string;
73
+ maxAge: number;
74
+ }
75
+ export interface CacheConfig {
76
+ enabled: boolean;
77
+ type: CacheType;
78
+ ttl: number;
79
+ max?: number;
80
+ redis?: {
81
+ url: string;
82
+ prefix: string;
83
+ maxRetries: number;
84
+ connectTimeout: number;
85
+ cluster?: {
86
+ nodes: string[];
87
+ options?: {
88
+ scaleReads: 'master' | 'slave' | 'all';
89
+ maxRedirections: number;
90
+ };
91
+ };
92
+ };
93
+ customAdapter?: CacheAdapter<unknown>;
94
+ routeCache?: {
95
+ enabled: boolean;
96
+ ttl: number;
97
+ methods: string[];
98
+ excludePaths: string[];
99
+ varyByHeaders: string[];
100
+ varyByQuery: string[];
101
+ maxSize?: number;
102
+ purgeConditions?: {
103
+ maxAge: number;
104
+ maxItems: number;
105
+ lowMemory: boolean;
106
+ };
107
+ };
108
+ strategies?: {
109
+ [key: string]: {
110
+ type: CacheStrategy;
111
+ ttl: number;
112
+ staleWhileRevalidateTtl?: number;
113
+ };
114
+ };
115
+ }
116
+ export interface PerformanceConfig {
117
+ cache: CacheConfig;
118
+ prefetch: {
119
+ enabled: boolean;
120
+ paths: string[];
121
+ maxConcurrent: number;
122
+ preloadPatterns?: string[];
123
+ warmupStrategy?: 'gradual' | 'aggressive';
124
+ prefetchHeaders?: Record<string, string>;
125
+ };
126
+ optimization: {
127
+ minify: boolean;
128
+ compress: boolean;
129
+ treeshake: boolean;
130
+ lazyLoad: boolean;
131
+ chunkSize: number;
132
+ imageOptimization?: {
133
+ enabled: boolean;
134
+ quality: number;
135
+ formats: ('webp' | 'avif' | 'jpeg' | 'png')[];
136
+ maxWidth: number;
137
+ responsive: boolean;
138
+ };
139
+ fontOptimization?: {
140
+ enabled: boolean;
141
+ inlineSize: number;
142
+ preload: boolean;
143
+ formats: ('woff2' | 'woff')[];
144
+ };
145
+ cssOptimization?: {
146
+ minify: boolean;
147
+ purge: boolean;
148
+ splitChunks: boolean;
149
+ criticalPath: boolean;
150
+ };
151
+ };
152
+ monitoring?: {
153
+ enabled?: boolean;
154
+ sampleRate?: number;
155
+ metrics?: {
156
+ responseTime?: boolean;
157
+ memoryUsage?: boolean;
158
+ cpuUsage?: boolean;
159
+ errorRate?: boolean;
160
+ requestRate?: boolean;
161
+ cacheStats?: boolean;
162
+ };
163
+ tracing?: {
164
+ enabled?: boolean;
165
+ sampleRate?: number;
166
+ serviceName?: string;
167
+ serviceVersion?: string;
168
+ environment?: string;
169
+ jaegerEndpoint?: string;
170
+ zipkinEndpoint?: string;
171
+ };
172
+ storage?: {
173
+ type?: CacheType;
174
+ maxEntries?: number;
175
+ filePath?: string;
176
+ customHandler?: (metrics: MetricEntry[]) => Promise<void>;
177
+ };
178
+ alerting?: {
179
+ enabled?: boolean;
180
+ thresholds?: {
181
+ responseTime?: number;
182
+ errorRate?: number;
183
+ memoryUsage?: number;
184
+ };
185
+ webhookUrl?: string;
186
+ slackWebhook?: string;
187
+ emailConfig?: {
188
+ smtp?: {
189
+ host?: string;
190
+ port?: number;
191
+ secure?: boolean;
192
+ auth?: {
193
+ user?: string;
194
+ pass?: string;
195
+ };
196
+ };
197
+ to?: string[];
198
+ from?: string;
199
+ cache: boolean;
200
+ queue: boolean;
201
+ };
202
+ };
203
+ profiling?: {
204
+ enabled: boolean;
205
+ sampleRate: number;
206
+ includeHeapSnapshot: boolean;
207
+ gcStats: boolean;
208
+ };
209
+ logging: {
210
+ level: 'debug' | 'info' | 'warn' | 'error';
211
+ format: 'json' | 'pretty';
212
+ destination: 'console' | 'file';
213
+ rotation?: {
214
+ size: string;
215
+ interval: string;
216
+ maxFiles: number;
217
+ };
218
+ };
219
+ };
220
+ }
221
+ export interface LoadBalancerConfig {
222
+ enabled: boolean;
223
+ strategy: 'round-robin' | 'least-connections' | 'ip-hash' | 'weighted-round-robin' | 'fastest-response';
224
+ healthCheck: {
225
+ enabled: boolean;
226
+ interval: number;
227
+ timeout: number;
228
+ unhealthyThreshold: number;
229
+ healthyThreshold: number;
230
+ path: string;
231
+ expectedStatus?: number;
232
+ expectedBody?: string;
233
+ headers?: Record<string, string>;
234
+ };
235
+ sticky: {
236
+ enabled: boolean;
237
+ cookieName: string;
238
+ ttl: number;
239
+ secret?: string;
240
+ path?: string;
241
+ domain?: string;
242
+ };
243
+ retries: {
244
+ attempts: number;
245
+ timeout: number;
246
+ codes: number[];
247
+ backoff?: {
248
+ type: 'fixed' | 'exponential' | 'fibonacci';
249
+ initialDelay: number;
250
+ maxDelay: number;
251
+ factor: number;
252
+ };
253
+ };
254
+ nodes?: {
255
+ [key: string]: {
256
+ url: string;
257
+ weight?: number;
258
+ backup?: boolean;
259
+ maxFails?: number;
260
+ failTimeout?: number;
261
+ };
262
+ };
263
+ }
264
+ export interface SecurityConfig {
265
+ schemes: Record<string, SecurityScheme>;
266
+ rateLimit: RateLimitConfig & {
267
+ advanced?: {
268
+ tokensPerInterval: number;
269
+ interval: number;
270
+ burst?: number;
271
+ skipFailedRequests?: boolean;
272
+ keyGenerator?: (req: Request) => string;
273
+ };
274
+ stores?: {
275
+ type: 'memory' | 'redis';
276
+ redis?: {
277
+ url: string;
278
+ prefix: string;
279
+ };
280
+ };
281
+ };
282
+ cors: CorsConfig & {
283
+ preflightContinue?: boolean;
284
+ optionsSuccessStatus?: number;
285
+ privateNetworkAccess?: boolean;
286
+ exposedHeaders?: string[];
287
+ };
288
+ csrf: {
289
+ enabled: boolean;
290
+ secret: string;
291
+ cookie: {
292
+ name: string;
293
+ options: {
294
+ httpOnly: boolean;
295
+ secure: boolean;
296
+ sameSite: 'strict' | 'lax' | 'none';
297
+ };
298
+ };
299
+ ignoreMethods?: string[];
300
+ ignorePaths?: string[];
301
+ tokenLength?: number;
302
+ };
303
+ helmet: {
304
+ enabled: boolean;
305
+ contentSecurityPolicy: boolean | {
306
+ directives: Record<string, string[]>;
307
+ reportOnly?: boolean;
308
+ reportUri?: string;
309
+ upgradeInsecureRequests?: boolean;
310
+ blockAllMixedContent?: boolean;
311
+ };
312
+ crossOriginEmbedderPolicy?: boolean | {
313
+ policy?: 'require-corp' | 'credentialless';
314
+ };
315
+ crossOriginOpenerPolicy?: boolean | {
316
+ policy?: 'same-origin' | 'same-origin-allow-popups' | 'unsafe-none';
317
+ };
318
+ crossOriginResourcePolicy?: boolean | {
319
+ policy?: 'same-site' | 'same-origin' | 'cross-origin';
320
+ };
321
+ dnsPrefetchControl?: boolean | {
322
+ allow?: boolean;
323
+ };
324
+ xssFilter: boolean | {
325
+ setOnOldIE?: boolean;
326
+ };
327
+ noSniff: boolean;
328
+ frameOptions: 'DENY' | 'SAMEORIGIN';
329
+ hidePoweredBy: boolean;
330
+ hsts?: {
331
+ maxAge: number;
332
+ includeSubDomains: boolean;
333
+ preload: boolean;
334
+ };
335
+ referrerPolicy?: string | {
336
+ policy?: string | string[];
337
+ };
338
+ expectCt?: {
339
+ enforce: boolean;
340
+ maxAge: number;
341
+ reportUri?: string;
342
+ };
343
+ ieNoOpen?: boolean;
344
+ originAgentCluster?: boolean;
345
+ permittedCrossDomainPolicies?: boolean | {
346
+ permittedPolicies?: 'none' | 'master-only' | 'by-content-type' | 'all';
347
+ };
348
+ };
349
+ ddos?: {
350
+ enabled?: boolean;
351
+ maxRequestsPerSecond?: number;
352
+ maxRequestsPerMinute?: number;
353
+ maxRequestsPerHour?: number;
354
+ burstLimit?: number;
355
+ windowSize?: number;
356
+ blockDuration?: number;
357
+ whitelistedIPs?: string[];
358
+ blacklistedIPs?: string[];
359
+ trustProxy?: boolean;
360
+ skipSuccessfulRequests?: boolean;
361
+ skipFailedRequests?: boolean;
362
+ keyGenerator?: (req: Request) => string;
363
+ store?: Extract<CacheType, 'memory' | 'redis'>;
364
+ redis?: {
365
+ url: string;
366
+ prefix?: string;
367
+ };
368
+ };
369
+ inputValidation?: {
370
+ enabled?: boolean;
371
+ sanitizeByDefault?: boolean;
372
+ strictMode?: boolean;
373
+ allowUnknownFields?: boolean;
374
+ maxDepth?: number;
375
+ schemas?: InputValidationSchemas;
376
+ };
377
+ attackPrevention?: {
378
+ enabled?: boolean;
379
+ sqlInjection?: boolean;
380
+ xss?: boolean;
381
+ pathTraversal?: boolean;
382
+ commandInjection?: boolean;
383
+ ldapInjection?: boolean;
384
+ xxe?: boolean;
385
+ customPatterns?: {
386
+ name: string;
387
+ pattern: RegExp;
388
+ action: 'block' | 'log' | 'sanitize';
389
+ }[];
390
+ };
391
+ requestFiltering?: {
392
+ enabled?: boolean;
393
+ blockSuspiciousPatterns?: boolean;
394
+ maxRequestsPerMinute?: number;
395
+ blockUserAgents?: string[];
396
+ allowedMethods?: string[];
397
+ requireUserAgent?: boolean;
398
+ maxBodySize?: number;
399
+ maxUrlLength?: number;
400
+ maxHeaderSize?: number;
401
+ allowedContentTypes?: string[];
402
+ };
403
+ ipFiltering?: {
404
+ enabled?: boolean;
405
+ whitelist?: string[];
406
+ blacklist?: string[];
407
+ blockPrivateIPs?: boolean;
408
+ blockCloudProviders?: boolean;
409
+ geoBlocking?: {
410
+ enabled?: boolean;
411
+ allowedCountries?: string[];
412
+ blockedCountries?: string[];
413
+ };
414
+ };
415
+ responseSecurity?: {
416
+ enabled?: boolean;
417
+ removeServerHeaders?: boolean;
418
+ addSecurityHeaders?: boolean;
419
+ sanitizeErrors?: boolean;
420
+ preventInfoDisclosure?: boolean;
421
+ };
422
+ auth: {
423
+ jwt: {
424
+ secret: string;
425
+ expiresIn: string;
426
+ algorithm: 'HS256' | 'HS384' | 'HS512' | 'RS256';
427
+ issuer?: string;
428
+ audience?: string;
429
+ refreshToken?: {
430
+ enabled: boolean;
431
+ expiresIn: string;
432
+ renewBeforeExpiry?: number;
433
+ };
434
+ rotation?: {
435
+ enabled: boolean;
436
+ interval: number;
437
+ maxAge: number;
438
+ };
439
+ };
440
+ session: {
441
+ enabled: boolean;
442
+ secret: string;
443
+ name: string;
444
+ resave: boolean;
445
+ rolling: boolean;
446
+ saveUninitialized: boolean;
447
+ cookie: {
448
+ maxAge: number;
449
+ secure: boolean;
450
+ httpOnly: boolean;
451
+ sameSite: 'strict' | 'lax' | 'none';
452
+ domain?: string;
453
+ path?: string;
454
+ };
455
+ store?: {
456
+ type: CacheType;
457
+ redis?: {
458
+ url: string;
459
+ prefix: string;
460
+ ttl?: number;
461
+ scanCount?: number;
462
+ serializer?: SessionSerializer;
463
+ };
464
+ custom?: SessionStore;
465
+ };
466
+ };
467
+ oauth2?: {
468
+ enabled: boolean;
469
+ providers: {
470
+ [key: string]: {
471
+ clientId: string;
472
+ clientSecret: string;
473
+ callbackURL: string;
474
+ scope: string[];
475
+ authorizationURL?: string;
476
+ tokenURL?: string;
477
+ profileURL?: string;
478
+ validateProfile?: (profile: OAuth2Profile) => Promise<boolean>;
479
+ };
480
+ };
481
+ };
482
+ };
483
+ encryption?: {
484
+ enabled: boolean;
485
+ algorithm: string;
486
+ key: string;
487
+ iv?: string;
488
+ encoding: 'hex' | 'base64';
489
+ };
490
+ sanitization?: {
491
+ enabled: boolean;
492
+ rules: {
493
+ [key: string]: {
494
+ type: 'escape' | 'strip' | 'validate';
495
+ options?: SanitizationOptions;
496
+ };
497
+ };
498
+ };
499
+ }
500
+ export interface ServerConfig {
501
+ port: number;
502
+ hostname: string;
503
+ development: boolean;
504
+ cors: CorsConfig;
505
+ rateLimit: RateLimitConfig;
506
+ compression: CompressionConfig;
507
+ static: StaticConfig;
508
+ performance: PerformanceConfig;
509
+ loadBalancer?: LoadBalancerConfig;
510
+ security: SecurityConfig;
511
+ cluster: {
512
+ enabled: boolean;
513
+ workers: number | 'auto';
514
+ sticky: boolean;
515
+ strategy?: 'rr' | 'lc';
516
+ maxMemory?: number;
517
+ restartOnMemory?: boolean;
518
+ ipcTimeout?: number;
519
+ };
520
+ gracefulShutdown: {
521
+ enabled: boolean;
522
+ timeout: number;
523
+ signals: string[];
524
+ forceTimeout: number;
525
+ preShutdown?: () => Promise<void>;
526
+ drain?: {
527
+ enabled: boolean;
528
+ timeout: number;
529
+ waitForStreams: boolean;
530
+ };
531
+ };
532
+ middleware: {
533
+ errorHandler?: (error: Error, req: Request) => Promise<Response>;
534
+ notFound?: (req: Request) => Promise<Response>;
535
+ timeout?: number;
536
+ order?: string[];
537
+ global?: MiddlewareHandler[];
538
+ };
539
+ hooks: {
540
+ onStart?: () => Promise<void>;
541
+ onStop?: () => Promise<void>;
542
+ onRequest?: (req: Request) => Promise<Request | Response>;
543
+ onResponse?: (res: Response) => Promise<Response>;
544
+ onError?: (error: Error) => Promise<void>;
545
+ onMetric?: (metric: {
546
+ name: string;
547
+ value: number;
548
+ tags?: Record<string, string>;
549
+ }) => Promise<void>;
550
+ onTrace?: (span: TraceSpan) => Promise<void>;
551
+ };
552
+ experimental?: {
553
+ http3: boolean;
554
+ webTransport: boolean;
555
+ earlyHints: boolean;
556
+ webSocket: {
557
+ enabled: boolean;
558
+ compression?: boolean;
559
+ maxPayload?: number;
560
+ };
561
+ };
562
+ }
563
+ export interface ViewEngineConfig {
564
+ /**
565
+ * The path to view files
566
+ */
567
+ viewsPath: string;
568
+ /**
569
+ * File extensions to look for when resolving views
570
+ */
571
+ extensions: string[];
572
+ /**
573
+ * Default layout to use for views
574
+ */
575
+ defaultLayout?: string;
576
+ /**
577
+ * Whether to cache compiled templates
578
+ */
579
+ cache: boolean;
580
+ /**
581
+ * Template engine to use
582
+ */
583
+ engine: TemplateEngine;
584
+ /**
585
+ * Custom render function for template processing
586
+ */
587
+ customRenderer?: (template: string, data: Record<string, any>, options: ViewRenderOptions) => Promise<string>;
588
+ /**
589
+ * HTML minification options
590
+ */
591
+ minify?: {
592
+ enabled: boolean;
593
+ options?: {
594
+ removeComments?: boolean;
595
+ collapseWhitespace?: boolean;
596
+ conservativeCollapse?: boolean;
597
+ minifyJS?: boolean;
598
+ minifyCSS?: boolean;
599
+ };
600
+ };
601
+ /**
602
+ * Template helpers
603
+ */
604
+ helpers?: TemplateHelpers;
605
+ }
606
+ export interface ViewRenderOptions {
607
+ layout?: string;
608
+ partials?: Record<string, string>;
609
+ components?: Record<string, string>;
610
+ helpers?: TemplateHelpers;
611
+ sections?: Record<string, string>;
612
+ }
613
+ export interface RouterConfig {
614
+ verbose: boolean;
615
+ routesPath?: string;
616
+ apiRoutesPath?: string;
617
+ webRoutesPath?: string;
618
+ apiPrefix?: string;
619
+ webPrefix?: string;
620
+ /**
621
+ * Base path for action handlers (default: 'actions')
622
+ * Used when resolving string-based handlers like 'UserAction.ts'
623
+ */
624
+ actionsPath?: string;
625
+ /**
626
+ * Base path for controllers (default: 'controllers')
627
+ * Used when resolving Controller@method patterns
628
+ */
629
+ controllersPath?: string;
630
+ defaultMiddleware?: {
631
+ api?: (string | MiddlewareHandler)[];
632
+ web?: (string | MiddlewareHandler)[];
633
+ };
634
+ /**
635
+ * View engine configuration
636
+ */
637
+ views?: ViewEngineConfig;
638
+ docs?: DocsConfig;
639
+ server?: ServerConfig;
640
+ /**
641
+ * Query parameter preservation configuration
642
+ * Automatically preserves specified query parameters across navigation
643
+ * @example
644
+ * queryPreservation: {
645
+ * preserve: ['siteId', 'theme', 'locale'],
646
+ * exclude: ['_t', 'utm_source'],
647
+ * routes: ['/dashboard/*', '/admin/*']
648
+ * }
649
+ */
650
+ queryPreservation?: QueryPreservationConfig;
651
+ }
652
+ export type RouterOptions = Partial<RouterConfig>;
653
+ export interface RouteParams {
654
+ [key: string]: string;
655
+ }
656
+ /**
657
+ * Cookie map interface for working with cookies
658
+ */
659
+ export interface CookieMap {
660
+ get: (name: string) => string | undefined;
661
+ set: (name: string, value: string, options?: CookieOptions) => void;
662
+ delete: (name: string, options?: Pick<CookieOptions, 'path' | 'domain'>) => void;
663
+ getAll: () => Record<string, string>;
664
+ }
665
+ /**
666
+ * Cookie options interface
667
+ */
668
+ export interface CookieOptions {
669
+ maxAge?: number;
670
+ expires?: Date;
671
+ httpOnly?: boolean;
672
+ secure?: boolean;
673
+ path?: string;
674
+ domain?: string;
675
+ sameSite?: 'strict' | 'lax' | 'none';
676
+ }
677
+ /**
678
+ * Cookie accessor interface with utility methods
679
+ */
680
+ export interface CookieAccessor {
681
+ get: (name: string) => string | undefined;
682
+ set: (name: string, value: string, options?: CookieOptions) => void;
683
+ delete: (name: string, options?: CookieOptions) => void;
684
+ getAll: () => Record<string, string>;
685
+ }
686
+ export interface EnhancedRequest extends Request, Omit<RequestMacroMethods, 'ip' | 'cookies' | 'route'> {
687
+ /**
688
+ * Route parameters extracted from the URL
689
+ */
690
+ params: Record<string, string>;
691
+ /**
692
+ * Query parameters from the URL
693
+ */
694
+ query: Record<string, string | string[]>;
695
+ /**
696
+ * Parsed JSON body (if Content-Type is application/json)
697
+ */
698
+ jsonBody?: Record<string, unknown>;
699
+ /**
700
+ * Form body data (if Content-Type is multipart/form-data or application/x-www-form-urlencoded)
701
+ */
702
+ formBody?: FormBody;
703
+ /**
704
+ * Uploaded files (if Content-Type is multipart/form-data)
705
+ */
706
+ files?: UploadedFile[];
707
+ /**
708
+ * Session data (if session middleware is used)
709
+ */
710
+ session?: SessionData;
711
+ /**
712
+ * User data (if authentication middleware is used)
713
+ */
714
+ user?: User;
715
+ /**
716
+ * Additional context data that can be set by middleware
717
+ */
718
+ context?: RequestContext;
719
+ /**
720
+ * Validated data from validation middleware
721
+ */
722
+ validated?: ValidatedData;
723
+ /**
724
+ * Model binding data
725
+ */
726
+ models?: BoundModels;
727
+ /**
728
+ * Model binding errors
729
+ */
730
+ modelErrors?: Record<string, string>;
731
+ /**
732
+ * Authenticated user from auth middleware
733
+ */
734
+ auth?: AuthContext;
735
+ /**
736
+ * Rate limiting information
737
+ */
738
+ rateLimitRemaining?: number;
739
+ /**
740
+ * Request ID for tracing
741
+ */
742
+ requestId?: string;
743
+ /**
744
+ * IP address of the client (string property, not function from RequestMacroMethods)
745
+ */
746
+ ip?: string;
747
+ /**
748
+ * Cookies parsed from the request with utility methods
749
+ */
750
+ cookies?: CookieAccessor;
751
+ /**
752
+ * Flash messages (temporary messages for the next request)
753
+ */
754
+ flash?: FlashMessages;
755
+ /**
756
+ * CSRF token
757
+ */
758
+ csrfToken?: string;
759
+ /**
760
+ * Request start time for performance monitoring
761
+ */
762
+ startTime?: number;
763
+ /**
764
+ * Trace ID for distributed tracing
765
+ */
766
+ traceId?: string;
767
+ /**
768
+ * Span ID for distributed tracing
769
+ */
770
+ spanId?: string;
771
+ /**
772
+ * Security middleware additions
773
+ */
774
+ nonce?: string;
775
+ validatedBody?: ValidatedBody;
776
+ /**
777
+ * Internal cookies to set in response (used by cookie utilities)
778
+ */
779
+ _cookiesToSet?: CookieToSet[];
780
+ /**
781
+ * Internal cookies to delete in response (used by cookie utilities)
782
+ */
783
+ _cookiesToDelete?: CookieToDelete[];
784
+ /**
785
+ * SSE connection information
786
+ */
787
+ sse?: SSEConnection;
788
+ /**
789
+ * The matched route object
790
+ */
791
+ route?: Route;
792
+ }
793
+ export interface UploadedFile {
794
+ fieldName: string;
795
+ originalName: string;
796
+ filename: string;
797
+ path: string;
798
+ size: number;
799
+ mimetype: string;
800
+ buffer: ArrayBuffer;
801
+ }
802
+ export type RouteHandler = (_req: EnhancedRequest) => Response | Promise<Response>;
803
+ /**
804
+ * Interface for handling route actions.
805
+ * All action handlers must implement this interface.
806
+ */
807
+ export interface ActionHandlerClass {
808
+ /**
809
+ * Handles an incoming HTTP request and returns a response.
810
+ * @param request The incoming HTTP request
811
+ * @returns A Promise that resolves to a Response object
812
+ */
813
+ handle: (request: EnhancedRequest) => Promise<Response>;
814
+ }
815
+ /**
816
+ * Action handler path with strict pattern validation
817
+ */
818
+ export type ActionPath = `Actions/${string}Action` | `actions/${string}Action` | `${string}Controller@${string}`;
819
+ /**
820
+ * Strongly typed action handler with better type safety
821
+ */
822
+ export type ActionHandler<TPath extends string = string> = ActionPath | TypedRouteHandler<TPath> | RouteHandler | (new () => ActionHandlerClass) | Response;
823
+ /**
824
+ * Controller method reference with strict typing
825
+ */
826
+ export type ControllerMethod<TController extends string = string, TMethod extends string = string> = `${TController}@${TMethod}`;
827
+ /**
828
+ * Action class constructor with typed handle method
829
+ */
830
+ export interface TypedActionHandlerClass<TPath extends string = string> {
831
+ handle: (request: EnhancedRequest & {
832
+ params: ExtractRouteParams<TPath>;
833
+ }) => Promise<Response>;
834
+ }
835
+ /**
836
+ * Discriminated union for different action handler types
837
+ */
838
+ export type ActionHandlerVariant<TPath extends string = string> = {
839
+ type: 'path';
840
+ value: ActionPath;
841
+ } | {
842
+ type: 'function';
843
+ value: TypedRouteHandler<TPath>;
844
+ } | {
845
+ type: 'class';
846
+ value: new () => TypedActionHandlerClass<TPath>;
847
+ } | {
848
+ type: 'controller';
849
+ value: ControllerMethod;
850
+ };
851
+ export type NextFunction = () => Promise<Response | null> | Response | null;
852
+ export type MiddlewareHandler = (_req: EnhancedRequest, _next: NextFunction) => Promise<Response | null> | Response | null;
853
+ export interface Middleware {
854
+ handle: MiddlewareHandler;
855
+ }
856
+ /**
857
+ * Strict middleware configuration with narrow types
858
+ */
859
+ export interface StrictMiddlewareConfig {
860
+ name: BuiltInMiddleware;
861
+ enabled: boolean;
862
+ priority: number;
863
+ timing: MiddlewareTiming;
864
+ params?: Record<string, string | number | boolean>;
865
+ }
866
+ /**
867
+ * Conditional middleware with narrow type constraints
868
+ */
869
+ export interface ConditionalMiddleware<T extends BuiltInMiddleware = BuiltInMiddleware> {
870
+ name: T;
871
+ condition: (req: EnhancedRequest) => boolean;
872
+ handler: MiddlewareHandler;
873
+ priority?: number;
874
+ }
875
+ /**
876
+ * Middleware group configuration with strict typing
877
+ */
878
+ export interface MiddlewareGroup {
879
+ name: string;
880
+ middleware: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware>)[];
881
+ priority: number;
882
+ description?: string;
883
+ }
884
+ /**
885
+ * Throttle middleware parameters with narrow types
886
+ */
887
+ export interface ThrottleMiddlewareParams {
888
+ pattern: ThrottlePattern;
889
+ name?: string;
890
+ keyGenerator?: (req: EnhancedRequest) => string;
891
+ skipIf?: (req: EnhancedRequest) => boolean;
892
+ }
893
+ /**
894
+ * CORS middleware configuration with strict options
895
+ */
896
+ export interface CorsMiddlewareConfig {
897
+ origin: string | string[] | boolean | ((_origin: string) => boolean);
898
+ methods: HTTPMethod[];
899
+ allowedHeaders: string[];
900
+ exposedHeaders?: string[];
901
+ credentials: boolean;
902
+ maxAge: number;
903
+ preflightContinue: boolean;
904
+ optionsSuccessStatus: ResponseStatus;
905
+ }
906
+ /**
907
+ * Auth middleware configuration with narrow types
908
+ */
909
+ export interface AuthMiddlewareConfig {
910
+ type: 'jwt' | 'session' | 'apikey' | 'basic' | 'bearer';
911
+ required: boolean;
912
+ realm?: string;
913
+ validateUser?: (user: User) => boolean;
914
+ onUnauthorized?: (req: EnhancedRequest) => Response;
915
+ }
916
+ export interface RouteGroup {
917
+ prefix?: string;
918
+ middleware?: (string | MiddlewareHandler)[];
919
+ }
920
+ export interface Route {
921
+ path: string;
922
+ handler: ActionHandler;
923
+ method: string;
924
+ middleware: MiddlewareHandler[];
925
+ type?: 'api' | 'web';
926
+ name?: string;
927
+ constraints?: Record<string, string> | ((_params: Record<string, string>) => boolean)[];
928
+ domain?: string;
929
+ params?: Record<string, string>;
930
+ pattern?: {
931
+ exec: (url: URL) => PatternMatchResult | null;
932
+ };
933
+ }
934
+ /**
935
+ * WebSocket handler configuration
936
+ */
937
+ export interface WebSocketConfig<T extends WebSocketData = WebSocketData> {
938
+ open?: (ws: TypedServerWebSocket<T>) => void | Promise<void>;
939
+ message: (ws: TypedServerWebSocket<T>, message: string | Uint8Array | ArrayBuffer) => void | Promise<void>;
940
+ close?: (ws: TypedServerWebSocket<T>, code: number, reason: string) => void | Promise<void>;
941
+ ping?: (ws: TypedServerWebSocket<T>, data: Uint8Array) => void | Promise<void>;
942
+ pong?: (ws: TypedServerWebSocket<T>, data: Uint8Array) => void | Promise<void>;
943
+ drain?: (ws: TypedServerWebSocket<T>) => void | Promise<void>;
944
+ error?: (ws: TypedServerWebSocket<T>, error: Error) => void | Promise<void>;
945
+ maxPayloadLength?: number;
946
+ backpressureLimit?: number;
947
+ closeOnBackpressureLimit?: boolean;
948
+ idleTimeout?: number;
949
+ perMessageDeflate?: boolean | {
950
+ compress?: boolean | Compressor;
951
+ decompress?: boolean | Compressor;
952
+ };
953
+ sendPings?: boolean;
954
+ publishToSelf?: boolean;
955
+ }
956
+ export type Compressor = 'disable' | 'shared' | 'dedicated' | '3KB' | '4KB' | '8KB' | '16KB' | '32KB' | '64KB' | '128KB' | '256KB';
957
+ export interface ServerOptions<T extends WebSocketData = WebSocketData> extends Partial<Omit<Server<T>, 'websocket' | 'development'>> {
958
+ websocket?: WebSocketConfig<T>;
959
+ /**
960
+ * Pre-computed static responses served by Bun's native static dispatch.
961
+ * These bypass the fetch handler entirely for zero-allocation serving (~15% faster).
962
+ */
963
+ static?: Record<string, Response>;
964
+ /**
965
+ * Development mode options for Bun's dev server.
966
+ * When true, enables HMR and development features.
967
+ * When an object, allows fine-grained control over HMR and console streaming.
968
+ *
969
+ * @example
970
+ * // Stream browser console.log/console.error to terminal
971
+ * development: { console: true }
972
+ *
973
+ * // Enable HMR + console streaming
974
+ * development: { hmr: true, console: true }
975
+ */
976
+ development?: boolean | {
977
+ hmr?: boolean;
978
+ console?: boolean;
979
+ };
980
+ }
981
+ /**
982
+ * Type definition for route configuration with strict typing.
983
+ */
984
+ export interface RouteDefinition<TPath extends string = string, TMethod extends HTTPMethod = HTTPMethod, THandler extends ActionHandler = ActionHandler> {
985
+ /**
986
+ * The path pattern for the route
987
+ */
988
+ path: TPath;
989
+ /**
990
+ * The HTTP method for the route
991
+ */
992
+ method: TMethod;
993
+ /**
994
+ * The action handler for the route - can be a string path, function, or class
995
+ */
996
+ handler: THandler;
997
+ /**
998
+ * Optional array of middleware to be executed before the handler
999
+ */
1000
+ middleware?: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware> | MiddlewareHandler)[];
1001
+ /**
1002
+ * Optional route type to distinguish between API and web routes
1003
+ */
1004
+ type?: 'api' | 'web';
1005
+ /**
1006
+ * Optional route name for reverse routing
1007
+ */
1008
+ name?: string;
1009
+ /**
1010
+ * Route parameter constraints
1011
+ */
1012
+ constraints?: {
1013
+ [K in keyof ExtractRouteParams<TPath>]: RouteConstraint;
1014
+ };
1015
+ /**
1016
+ * Optional route metadata for documentation or other purposes
1017
+ */
1018
+ meta?: RouteMetadata;
1019
+ /**
1020
+ * Cache configuration for this specific route
1021
+ */
1022
+ cache?: {
1023
+ enabled: boolean;
1024
+ ttl: number;
1025
+ tags?: string[];
1026
+ strategy?: CacheStrategy;
1027
+ };
1028
+ /**
1029
+ * Rate limiting configuration for this route
1030
+ */
1031
+ throttle?: ThrottlePattern | ThrottleMiddlewareParams;
1032
+ }
1033
+ /**
1034
+ * HTTP Methods type - extremely narrow
1035
+ */
1036
+ export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' | 'TRACE' | 'CONNECT';
1037
+ /**
1038
+ * Narrow throttle pattern types
1039
+ */
1040
+ export type ThrottlePattern = `${number}` | `${number},${number}` | `${number},${number}min` | `${number},${number}m` | `${number},${number}sec` | `${number},${number}s` | `${number},${number}hour` | `${number},${number}h`;
1041
+ /**
1042
+ * Cache strategy types - narrow and specific
1043
+ */
1044
+ export type CacheStrategy = 'stale-while-revalidate' | 'cache-first' | 'network-first';
1045
+ /**
1046
+ * Cache type narrow definition
1047
+ */
1048
+ export type CacheType = 'memory' | 'redis' | 'custom';
1049
+ /**
1050
+ * File extension types for views
1051
+ */
1052
+ export type ViewExtension = '.html' | '.stx' | '.hbs' | '.ejs' | '.pug' | '.mustache';
1053
+ /**
1054
+ * Template engine types
1055
+ */
1056
+ export type TemplateEngine = 'auto' | 'stx' | 'html' | 'handlebars' | 'ejs' | 'pug' | 'mustache' | 'custom';
1057
+ /**
1058
+ * Route parameter constraint patterns
1059
+ */
1060
+ export type RouteConstraint = 'number' | 'alpha' | 'alphanumeric' | 'uuid' | 'slug' | RegExp | string;
1061
+ /**
1062
+ * Middleware execution timing
1063
+ */
1064
+ export type MiddlewareTiming = 'before' | 'after' | 'around';
1065
+ /**
1066
+ * Security header types
1067
+ */
1068
+ export type SecurityHeader = 'Content-Security-Policy' | 'X-Frame-Options' | 'X-Content-Type-Options' | 'Referrer-Policy' | 'Permissions-Policy' | 'Strict-Transport-Security';
1069
+ /**
1070
+ * Built-in middleware names - extremely narrow
1071
+ */
1072
+ export type BuiltInMiddleware = 'auth' | 'cors' | 'csrf' | 'helmet' | 'json' | 'compress' | 'static' | 'session' | 'rateLimiter' | 'requestId' | 'logger' | 'throttle';
1073
+ /**
1074
+ * Middleware with parameters
1075
+ */
1076
+ export type MiddlewareWithParams<T extends string = string> = T | `${T}:${string}`;
1077
+ /**
1078
+ * Route path parameter types - narrow template literals
1079
+ */
1080
+ export type RouteParam<T extends string> = T extends `{${infer P}}` ? P : never;
1081
+ /**
1082
+ * Extract parameters from route path
1083
+ */
1084
+ export type ExtractRouteParams<T extends string> = T extends `${string}{${infer Param}}${infer Rest}` ? {
1085
+ [K in Param]: string;
1086
+ } & ExtractRouteParams<Rest> : object;
1087
+ /**
1088
+ * Route method constraints
1089
+ */
1090
+ export type RouteMethodConstraint<M extends HTTPMethod = HTTPMethod> = M;
1091
+ /**
1092
+ * File MIME types for uploads
1093
+ */
1094
+ export type AllowedMimeType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/svg+xml' | 'application/pdf' | 'application/json' | 'text/plain' | 'text/csv' | 'application/octet-stream';
1095
+ /**
1096
+ * Response status codes - narrow and specific
1097
+ */
1098
+ export type ResponseStatus = 200 | 201 | 202 | 204 | 301 | 302 | 304 | 400 | 401 | 403 | 404 | 405 | 409 | 422 | 429 | 500 | 502 | 503 | 504;
1099
+ /**
1100
+ * Content types - narrow
1101
+ */
1102
+ export type ContentType = 'application/json' | 'application/xml' | 'text/html' | 'text/plain' | 'text/csv' | 'application/pdf' | 'application/octet-stream' | 'multipart/form-data' | 'application/x-www-form-urlencoded';
1103
+ /**
1104
+ * Strongly typed route method signatures
1105
+ */
1106
+ export interface TypedRouteHandler<TPath extends string> {
1107
+ (req: EnhancedRequest & {
1108
+ params: ExtractRouteParams<TPath>;
1109
+ }): Response | Promise<Response>;
1110
+ }
1111
+ /**
1112
+ * Strongly typed route definition for specific HTTP methods
1113
+ */
1114
+ export interface GetRoute<TPath extends string> extends RouteDefinition<TPath, 'GET'> {
1115
+ method: 'GET';
1116
+ handler: TypedRouteHandler<TPath> | ActionHandler;
1117
+ }
1118
+ export interface PostRoute<TPath extends string> extends RouteDefinition<TPath, 'POST'> {
1119
+ method: 'POST';
1120
+ handler: TypedRouteHandler<TPath> | ActionHandler;
1121
+ }
1122
+ export interface PutRoute<TPath extends string> extends RouteDefinition<TPath, 'PUT'> {
1123
+ method: 'PUT';
1124
+ handler: TypedRouteHandler<TPath> | ActionHandler;
1125
+ }
1126
+ export interface DeleteRoute<TPath extends string> extends RouteDefinition<TPath, 'DELETE'> {
1127
+ method: 'DELETE';
1128
+ handler: TypedRouteHandler<TPath> | ActionHandler;
1129
+ }
1130
+ export interface PatchRoute<TPath extends string> extends RouteDefinition<TPath, 'PATCH'> {
1131
+ method: 'PATCH';
1132
+ handler: TypedRouteHandler<TPath> | ActionHandler;
1133
+ }
1134
+ /**
1135
+ * Union of all typed route definitions
1136
+ */
1137
+ export type TypedRouteDefinition<TPath extends string = string> = GetRoute<TPath> | PostRoute<TPath> | PutRoute<TPath> | DeleteRoute<TPath> | PatchRoute<TPath>;
1138
+ /**
1139
+ * Route validation helpers
1140
+ */
1141
+ export interface RouteValidation<TPath extends string> {
1142
+ path: TPath;
1143
+ params: ExtractRouteParams<TPath>;
1144
+ validate: (req: EnhancedRequest) => req is EnhancedRequest & {
1145
+ params: ExtractRouteParams<TPath>;
1146
+ };
1147
+ }
1148
+ /**
1149
+ * Common route patterns with strict template literal types
1150
+ */
1151
+ export type CommonRoutePatterns = '/' | '/health' | '/api' | '/api/v1' | '/api/v1/users' | '/api/v1/users/{id}' | '/api/v1/users/{userId}/posts' | '/api/v1/users/{userId}/posts/{postId}' | '/admin' | '/admin/{section}' | '/auth/login' | '/auth/logout' | '/auth/register' | '/auth/forgot-password' | '/uploads/{filename}' | '/assets/{path}';
1152
+ /**
1153
+ * RESTful resource route patterns
1154
+ */
1155
+ export type ResourceRoutePatterns<T extends string> = `/${T}` | `/${T}/{id}` | `/${T}/create` | `/${T}/{id}/edit` | `/${T}/{id}/show`;
1156
+ /**
1157
+ * API versioning patterns
1158
+ */
1159
+ export type ApiVersionPattern<V extends string, Path extends string> = `/api/${V}${Path}`;
1160
+ /**
1161
+ * Nested resource patterns
1162
+ */
1163
+ export type NestedResourcePattern<Parent extends string, Child extends string, ParentId extends string = 'id', ChildId extends string = 'id'> = `/${Parent}/{${ParentId}}/${Child}` | `/${Parent}/{${ParentId}}/${Child}/{${ChildId}}`;
1164
+ /**
1165
+ * Route parameter patterns with constraints
1166
+ */
1167
+ export type IdPattern = '{id}';
1168
+ export type UuidPattern = '{uuid}';
1169
+ export type SlugPattern = '{slug}';
1170
+ export type NumberPattern = '{number}';
1171
+ /**
1172
+ * File path patterns
1173
+ */
1174
+ export type FilePathPattern = '{filepath}' | '{*filepath}' | '{path...}';
1175
+ /**
1176
+ * Discriminated union for cache configurations
1177
+ */
1178
+ export type CacheConfigVariant = {
1179
+ type: 'memory';
1180
+ maxSize: number;
1181
+ ttl: number;
1182
+ } | {
1183
+ type: 'redis';
1184
+ url: string;
1185
+ prefix: string;
1186
+ ttl: number;
1187
+ maxRetries: number;
1188
+ } | {
1189
+ type: 'custom';
1190
+ adapter: CacheConfig['customAdapter'];
1191
+ ttl: number;
1192
+ };
1193
+ /**
1194
+ * Discriminated union for authentication configurations
1195
+ */
1196
+ export type AuthConfigVariant = {
1197
+ type: 'jwt';
1198
+ secret: string;
1199
+ expiresIn: string;
1200
+ algorithm: 'HS256' | 'HS384' | 'HS512' | 'RS256';
1201
+ } | {
1202
+ type: 'session';
1203
+ secret: string;
1204
+ store: CacheType;
1205
+ maxAge: number;
1206
+ } | {
1207
+ type: 'apikey';
1208
+ keyName: string;
1209
+ location: 'header' | 'query' | 'cookie';
1210
+ } | {
1211
+ type: 'basic';
1212
+ realm: string;
1213
+ users: Record<string, string>;
1214
+ } | {
1215
+ type: 'bearer';
1216
+ validate: (token: string) => Promise<boolean>;
1217
+ };
1218
+ /**
1219
+ * Discriminated union for rate limiting configurations
1220
+ */
1221
+ export type RateLimitConfigVariant = {
1222
+ type: 'memory';
1223
+ maxAttempts: number;
1224
+ windowMs: number;
1225
+ keyGenerator?: (req: EnhancedRequest) => string;
1226
+ } | {
1227
+ type: 'redis';
1228
+ maxAttempts: number;
1229
+ windowMs: number;
1230
+ redisUrl: string;
1231
+ keyPrefix: string;
1232
+ } | {
1233
+ type: 'pattern';
1234
+ pattern: ThrottlePattern;
1235
+ name?: string;
1236
+ };
1237
+ /**
1238
+ * Discriminated union for middleware configurations
1239
+ */
1240
+ export type MiddlewareConfigVariant = {
1241
+ type: 'throttle';
1242
+ config: RateLimitConfigVariant;
1243
+ } | {
1244
+ type: 'cors';
1245
+ config: CorsMiddlewareConfig;
1246
+ } | {
1247
+ type: 'auth';
1248
+ config: AuthConfigVariant;
1249
+ } | {
1250
+ type: 'cache';
1251
+ config: CacheConfigVariant;
1252
+ } | {
1253
+ type: 'custom';
1254
+ name: string;
1255
+ handler: MiddlewareHandler;
1256
+ params?: MiddlewareParams;
1257
+ };
1258
+ /**
1259
+ * Discriminated union for route handlers
1260
+ */
1261
+ export type RouteHandlerVariant<TPath extends string = string> = {
1262
+ type: 'action';
1263
+ path: ActionPath;
1264
+ } | {
1265
+ type: 'function';
1266
+ handler: TypedRouteHandler<TPath>;
1267
+ } | {
1268
+ type: 'class';
1269
+ constructor: new () => TypedActionHandlerClass<TPath>;
1270
+ } | {
1271
+ type: 'controller';
1272
+ method: ControllerMethod;
1273
+ };
1274
+ /**
1275
+ * Discriminated union for validation rules
1276
+ */
1277
+ export type ValidationRuleVariant = {
1278
+ type: 'required';
1279
+ message?: string;
1280
+ } | {
1281
+ type: 'string';
1282
+ minLength?: number;
1283
+ maxLength?: number;
1284
+ pattern?: RegExp;
1285
+ } | {
1286
+ type: 'number';
1287
+ min?: number;
1288
+ max?: number;
1289
+ integer?: boolean;
1290
+ } | {
1291
+ type: 'email';
1292
+ message?: string;
1293
+ } | {
1294
+ type: 'url';
1295
+ protocols?: string[];
1296
+ } | {
1297
+ type: 'custom';
1298
+ validate: (value: unknown) => boolean | Promise<boolean>;
1299
+ message: string;
1300
+ };
1301
+ /**
1302
+ * Streaming configuration types with extreme narrowing
1303
+ */
1304
+ export type StreamingFormat = 'json' | 'ndjson' | 'csv' | 'xml' | 'text' | 'binary';
1305
+ export type StreamingCompression = 'gzip' | 'deflate' | 'br' | 'none';
1306
+ export type StreamingMode = 'chunked' | 'buffered' | 'direct';
1307
+ /**
1308
+ * Server-Sent Events configuration
1309
+ */
1310
+ export interface SSEConfig {
1311
+ retryInterval?: number;
1312
+ keepAlive?: number;
1313
+ compression?: StreamingCompression;
1314
+ maxConnections?: number;
1315
+ heartbeatInterval?: number;
1316
+ headers?: Record<string, string>;
1317
+ enableHeartbeat?: boolean;
1318
+ connectionTimeout?: number;
1319
+ retryDelay?: number;
1320
+ }
1321
+ /**
1322
+ * SSE Event data structure with strict typing
1323
+ */
1324
+ export interface SSEEvent<T = unknown> {
1325
+ data: T;
1326
+ event?: string;
1327
+ id?: string | number;
1328
+ retry?: number;
1329
+ comment?: string;
1330
+ }
1331
+ /**
1332
+ * Stream generator function types
1333
+ */
1334
+ export type SSEGenerator<T = unknown> = () => AsyncGenerator<SSEEvent<T>, void, unknown>;
1335
+ /**
1336
+ * Direct streaming configuration
1337
+ */
1338
+ export interface DirectStreamConfig {
1339
+ headers?: Record<string, string>;
1340
+ status?: ResponseStatus;
1341
+ compression?: StreamingCompression;
1342
+ format?: StreamingFormat;
1343
+ bufferSize?: number;
1344
+ delimiter?: string;
1345
+ contentType?: ContentType;
1346
+ enableCompression?: boolean;
1347
+ compressionType?: StreamingCompression;
1348
+ }
1349
+ /**
1350
+ * Buffered streaming configuration
1351
+ */
1352
+ export interface BufferedStreamConfig extends DirectStreamConfig {
1353
+ highWaterMark?: number;
1354
+ maxBuffer?: number;
1355
+ flushInterval?: number;
1356
+ autoFlush?: boolean;
1357
+ contentType?: ContentType;
1358
+ }
1359
+ /**
1360
+ * File streaming configuration with strict types
1361
+ */
1362
+ export interface FileStreamConfig {
1363
+ headers?: Record<string, string>;
1364
+ status?: ResponseStatus;
1365
+ mimeType?: AllowedMimeType;
1366
+ disposition?: 'inline' | 'attachment';
1367
+ filename?: string;
1368
+ maxAge?: number;
1369
+ etag?: boolean;
1370
+ lastModified?: boolean;
1371
+ compression?: StreamingCompression;
1372
+ }
1373
+ /**
1374
+ * Range request configuration for file streaming
1375
+ */
1376
+ export interface RangeStreamConfig extends FileStreamConfig {
1377
+ unit?: 'bytes';
1378
+ maxRanges?: number;
1379
+ enableMultipart?: boolean;
1380
+ }
1381
+ /**
1382
+ * Transform stream configuration
1383
+ */
1384
+ export interface TransformStreamConfig<TInput = any, TOutput = any> {
1385
+ transform: (chunk: TInput) => TOutput | Promise<TOutput>;
1386
+ flush?: () => TOutput[] | Promise<TOutput[]>;
1387
+ objectMode?: boolean;
1388
+ highWaterMark?: number;
1389
+ format?: StreamingFormat;
1390
+ headers?: Record<string, string>;
1391
+ }
1392
+ /**
1393
+ * Streaming response writer interfaces
1394
+ */
1395
+ export interface StreamWriter<T = any> {
1396
+ write: (chunk: T) => void | Promise<void>;
1397
+ end: () => void | Promise<void>;
1398
+ close: () => void;
1399
+ }
1400
+ export interface BufferedStreamWriterGeneric<T = any> extends StreamWriter<T> {
1401
+ flush: () => void | Promise<void>;
1402
+ cork: () => void;
1403
+ uncork: () => void;
1404
+ }
1405
+ /**
1406
+ * Model binding configuration with strict types
1407
+ */
1408
+ export interface ModelBinding<T = any> {
1409
+ name: string;
1410
+ model: string;
1411
+ parameter: string;
1412
+ required?: boolean;
1413
+ as?: string;
1414
+ resolver: ModelResolver<T>;
1415
+ cache?: {
1416
+ enabled: boolean;
1417
+ ttl: number;
1418
+ key?: (params: Record<string, string>) => string;
1419
+ };
1420
+ validation?: {
1421
+ required?: boolean;
1422
+ validator?: (model: T) => boolean | Promise<boolean>;
1423
+ };
1424
+ errorHandler?: (error: Error, params: Record<string, string>) => Response;
1425
+ }
1426
+ /**
1427
+ * Model resolver function type
1428
+ */
1429
+ export type ModelResolver<T = any> = (params: Record<string, string>, req: EnhancedRequest) => T | Promise<T> | null;
1430
+ /**
1431
+ * Model validator function type
1432
+ */
1433
+ export type ModelValidatorFn<T = any> = (model: T, params: Record<string, string>, req?: EnhancedRequest) => Promise<{
1434
+ valid: boolean;
1435
+ error?: string;
1436
+ status?: number;
1437
+ }> | {
1438
+ valid: boolean;
1439
+ error?: string;
1440
+ status?: number;
1441
+ };
1442
+ /**
1443
+ * Model transformer function type
1444
+ */
1445
+ export type ModelTransformerFn<T = any> = (model: T, params?: Record<string, string>, req?: EnhancedRequest) => any | Promise<any>;
1446
+ /**
1447
+ * Model registry interface
1448
+ */
1449
+ export interface ModelRegistry {
1450
+ register: <T>(binding: ModelBinding<T>) => void;
1451
+ resolve: <T>(name: string, params: Record<string, string>, req: EnhancedRequest) => Promise<T | null>;
1452
+ has: (name: string) => boolean;
1453
+ clear: () => void;
1454
+ getAll: () => ModelBinding[];
1455
+ }
1456
+ /**
1457
+ * Model binding middleware configuration
1458
+ */
1459
+ export interface ModelBindingConfig {
1460
+ parameterName: string;
1461
+ modelName: string;
1462
+ required?: boolean;
1463
+ cacheKey?: (params: Record<string, string>) => string;
1464
+ }
1465
+ /**
1466
+ * Resource route configuration with model binding
1467
+ */
1468
+ export interface ResourceConfig {
1469
+ controller: string;
1470
+ only?: ('index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy')[];
1471
+ except?: ('index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy')[];
1472
+ middleware?: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware>)[];
1473
+ bindings?: Record<string, string>;
1474
+ names?: Partial<Record<'index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy', string>>;
1475
+ }
1476
+ /**
1477
+ * Stream route handler with typed path parameters
1478
+ */
1479
+ export interface StreamRouteHandler<TPath extends string = string> {
1480
+ (req: EnhancedRequest & {
1481
+ params: ExtractRouteParams<TPath>;
1482
+ }, writer: StreamWriter): Promise<void> | void;
1483
+ }
1484
+ /**
1485
+ * SSE route handler with typed path parameters
1486
+ */
1487
+ export interface SSERouteHandler<TPath extends string = string> {
1488
+ (req: EnhancedRequest & {
1489
+ params: ExtractRouteParams<TPath>;
1490
+ }): SSEGenerator | AsyncGenerator<SSEEvent, void, unknown>;
1491
+ }
1492
+ /**
1493
+ * Route matching result
1494
+ */
1495
+ export interface MatchResult {
1496
+ route: Route;
1497
+ params: Record<string, string>;
1498
+ }
1499
+ /**
1500
+ * URL pattern match result
1501
+ */
1502
+ export interface PatternMatchResult {
1503
+ pathname: {
1504
+ groups: Record<string, string>;
1505
+ };
1506
+ }
1507
+ /**
1508
+ * Streaming response options
1509
+ */
1510
+ export interface StreamingOptions {
1511
+ headers?: Record<string, string>;
1512
+ status?: number;
1513
+ }
1514
+ /**
1515
+ * SSE (Server-Sent Events) data structure
1516
+ */
1517
+ export interface SSEData {
1518
+ data: any;
1519
+ event?: string;
1520
+ id?: string;
1521
+ retry?: number;
1522
+ }
1523
+ /**
1524
+ * Direct streaming writer interface
1525
+ */
1526
+ export interface DirectStreamWriter {
1527
+ write: (chunk: string | Uint8Array) => void;
1528
+ close: () => void;
1529
+ }
1530
+ /**
1531
+ * Buffered streaming writer interface
1532
+ */
1533
+ export interface BufferedStreamWriter {
1534
+ write: (chunk: string | Uint8Array) => void;
1535
+ flush: () => void;
1536
+ end: () => void;
1537
+ }
1538
+ /**
1539
+ * Buffered streaming options
1540
+ */
1541
+ export interface BufferedStreamOptions {
1542
+ highWaterMark?: number;
1543
+ asUint8Array?: boolean;
1544
+ }
1545
+ /**
1546
+ * Async generator function type for streaming
1547
+ */
1548
+ export type StreamGenerator<T = unknown> = () => AsyncGenerator<T, void, unknown>;
1549
+ /**
1550
+ * Direct stream handler function type
1551
+ */
1552
+ export type DirectStreamHandler = (_writer: DirectStreamWriter) => Promise<void>;
1553
+ /**
1554
+ * Buffered stream handler function type
1555
+ */
1556
+ export type BufferedStreamHandler = (_writer: BufferedStreamWriter) => Promise<void>;
1557
+ /**
1558
+ * Transform function type for stream transformation
1559
+ */
1560
+ export type TransformFunction<T = Uint8Array, R = string | Uint8Array> = (_chunk: T) => R | Promise<R>;
1561
+ /**
1562
+ * Advanced Error Handling Types
1563
+ */
1564
+ export interface ErrorContext {
1565
+ requestId?: string;
1566
+ userId?: string | number;
1567
+ traceId?: string;
1568
+ spanId?: string;
1569
+ route?: string;
1570
+ method?: string;
1571
+ url?: string;
1572
+ userAgent?: string;
1573
+ ip?: string;
1574
+ timestamp?: Date;
1575
+ metadata?: ErrorMetadata;
1576
+ }
1577
+ export interface ErrorReportingConfig {
1578
+ enabled: boolean;
1579
+ service: 'sentry' | 'bugsnag' | 'custom';
1580
+ dsn?: string;
1581
+ apiKey?: string;
1582
+ environment?: string;
1583
+ release?: string;
1584
+ sampleRate?: number;
1585
+ beforeSend?: (error: Error, context: ErrorContext) => Error | null;
1586
+ filters?: {
1587
+ ignoreErrors?: (string | RegExp)[];
1588
+ ignoreCodes?: string[];
1589
+ ignoreUrls?: (string | RegExp)[];
1590
+ allowUrls?: (string | RegExp)[];
1591
+ };
1592
+ tags?: Record<string, string>;
1593
+ user?: {
1594
+ id?: string;
1595
+ email?: string;
1596
+ username?: string;
1597
+ };
1598
+ extra?: Record<string, unknown>;
1599
+ breadcrumbs?: {
1600
+ enabled: boolean;
1601
+ maxBreadcrumbs: number;
1602
+ };
1603
+ performance?: {
1604
+ enabled: boolean;
1605
+ tracesSampleRate: number;
1606
+ };
1607
+ }
1608
+ export interface CircuitBreakerConfig {
1609
+ name: string;
1610
+ failureThreshold: number;
1611
+ recoveryTimeout: number;
1612
+ timeout: number;
1613
+ monitoringPeriod: number;
1614
+ minimumRequests: number;
1615
+ errorThresholdPercentage: number;
1616
+ halfOpenMaxCalls: number;
1617
+ resetTimeout: number;
1618
+ onStateChange?: (state: 'CLOSED' | 'OPEN' | 'HALF_OPEN', name: string) => void;
1619
+ onFailure?: (error: Error, name: string) => void;
1620
+ onSuccess?: (name: string) => void;
1621
+ shouldTripOnError?: (error: Error) => boolean;
1622
+ }
1623
+ export interface DegradationConfig {
1624
+ enabled: boolean;
1625
+ fallbackStrategies: {
1626
+ [serviceName: string]: {
1627
+ type: 'cache' | 'static' | 'simplified' | 'redirect' | 'custom';
1628
+ priority: number;
1629
+ timeout: number;
1630
+ retries: number;
1631
+ backoff: {
1632
+ type: 'fixed' | 'exponential';
1633
+ delay: number;
1634
+ maxDelay?: number;
1635
+ };
1636
+ fallbackHandler?: (error: FallbackError, context: ErrorContext) => Promise<Response>;
1637
+ cacheConfig?: {
1638
+ key: string;
1639
+ ttl: number;
1640
+ staleWhileRevalidate: boolean;
1641
+ };
1642
+ staticResponse?: {
1643
+ status: number;
1644
+ body: StaticResponseBody;
1645
+ headers?: Record<string, string>;
1646
+ };
1647
+ redirectConfig?: {
1648
+ url: string;
1649
+ permanent: boolean;
1650
+ };
1651
+ };
1652
+ };
1653
+ healthChecks: {
1654
+ [serviceName: string]: {
1655
+ enabled: boolean;
1656
+ endpoint: string;
1657
+ interval: number;
1658
+ timeout: number;
1659
+ retries: number;
1660
+ expectedStatus: number[];
1661
+ expectedBody?: string | RegExp;
1662
+ headers?: Record<string, string>;
1663
+ onHealthy?: () => void;
1664
+ onUnhealthy?: (error: Error) => void;
1665
+ };
1666
+ };
1667
+ monitoring: {
1668
+ enabled: boolean;
1669
+ alertThresholds: {
1670
+ errorRate: number;
1671
+ responseTime: number;
1672
+ availability: number;
1673
+ };
1674
+ };
1675
+ }
1676
+ /**
1677
+ * Request/Response Enhancement Types
1678
+ */
1679
+ export interface RequestMacroMethods {
1680
+ wantsJson: () => boolean;
1681
+ wantsHtml: () => boolean;
1682
+ wantsXml: () => boolean;
1683
+ expectsJson: () => boolean;
1684
+ isAjax: () => boolean;
1685
+ isPjax: () => boolean;
1686
+ isMobile: () => boolean;
1687
+ isBot: () => boolean;
1688
+ isSecure: () => boolean;
1689
+ ip: () => string;
1690
+ ips: () => string[];
1691
+ userAgent: () => string;
1692
+ referer: () => string | null;
1693
+ bearerToken: () => string | null;
1694
+ basicAuth: () => {
1695
+ username: string;
1696
+ password: string;
1697
+ } | null;
1698
+ hasHeader: (name: string) => boolean;
1699
+ header: (name: string, defaultValue?: string) => string | null;
1700
+ allHeaders: () => Record<string, string>;
1701
+ input: <T = InputValue>(key: string, defaultValue?: T) => T;
1702
+ all: () => RequestInput;
1703
+ only: (keys: string[]) => RequestInput;
1704
+ except: (keys: string[]) => RequestInput;
1705
+ has: (key: string) => boolean;
1706
+ hasAny: (keys: string[]) => boolean;
1707
+ missing: (key: string) => boolean;
1708
+ filled: (key: string) => boolean;
1709
+ getQuery: <T = InputValue>(key?: string, defaultValue?: T) => T;
1710
+ param: <T = InputValue>(key: string, defaultValue?: T) => T;
1711
+ cookie: (name: string, defaultValue?: string) => string | null;
1712
+ cookies: () => Record<string, string>;
1713
+ file: (name: string) => FileInfo | null;
1714
+ hasFile: (name: string) => boolean;
1715
+ path: () => string;
1716
+ fullUrl: () => string;
1717
+ root: () => string;
1718
+ is: (pattern: string) => boolean;
1719
+ route: () => string | null;
1720
+ fingerprint: () => string;
1721
+ signature: (secret: string) => string;
1722
+ merge: (data: RequestInput) => void;
1723
+ replace: (data: RequestInput) => void;
1724
+ age: () => number;
1725
+ isFromTrustedProxy: (trustedProxies?: string[]) => boolean;
1726
+ contentLength: () => number;
1727
+ contentType: () => string | null;
1728
+ isContentType: (type: string) => boolean;
1729
+ }
1730
+ /**
1731
+ * Enhanced streaming generator types with extreme narrowing
1732
+ */
1733
+ export type StreamGeneratorSync<T = string | Uint8Array> = () => Generator<T, void, unknown>;
1734
+ export type AsyncStreamGenerator<T = string | Uint8Array> = () => AsyncGenerator<T, void, unknown>;
1735
+ export type StreamCallbackGenerator<T = string | Uint8Array> = StreamGenerator<T> | AsyncStreamGenerator<T>;
1736
+ /**
1737
+ * SSE Event generator with strict typing
1738
+ */
1739
+ export type SSEEventGenerator<T = unknown> = () => Generator<SSEEvent<T>, void, unknown> | AsyncGenerator<SSEEvent<T>, void, unknown>;
1740
+ /**
1741
+ * Extreme narrow types for Laravel-style methods with template literal patterns
1742
+ */
1743
+ export interface EnhancedLaravelStreamingMethods {
1744
+ /**
1745
+ * Laravel-style response()->stream() with extreme type narrowing
1746
+ */
1747
+ stream: <T extends string | Uint8Array = string>(callback: StreamCallbackGenerator<T>, status?: ResponseStatus, headers?: Record<string, string>) => Response;
1748
+ /**
1749
+ * Laravel-style response()->streamJson() with strict object key typing
1750
+ */
1751
+ streamJson: <T, K extends string = string>(data: Record<K, Iterable<T> | AsyncIterable<T>>, status?: ResponseStatus, headers?: Record<string, string>) => Response;
1752
+ /**
1753
+ * Laravel-style response()->eventStream() with strict SSE typing
1754
+ */
1755
+ eventStream: <T = unknown>(callback: SSEEventGenerator<T>, headers?: Record<string, string>) => Response;
1756
+ /**
1757
+ * Laravel-style response()->streamDownload() with filename validation
1758
+ */
1759
+ streamDownload: <T extends string | Uint8Array = string>(callback: StreamCallbackGenerator<T>, filename: `${string}.${string}`, // Must have extension
1760
+ headers?: Record<string, string>) => Response;
1761
+ }
1762
+ /**
1763
+ * Enhanced model binding with strict key typing
1764
+ */
1765
+ export interface EnhancedLaravelModelBindingMethods {
1766
+ /**
1767
+ * Laravel-style Route::model() with key validation
1768
+ */
1769
+ model: <T, K extends string>(key: K, modelClass: string | ((_value: string) => Promise<T | null>), callback?: (model: T | null) => Response | null) => Router & {
1770
+ [P in K]: T;
1771
+ };
1772
+ /**
1773
+ * Scoped bindings with relationship validation
1774
+ */
1775
+ scopedBindings: <Parent extends string, Child extends string>(bindings: Record<Child, Parent>) => MiddlewareHandler;
1776
+ }