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