@stacksjs/bun-router 0.0.13 → 0.0.14

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 (273) hide show
  1. package/CHANGELOG.md +770 -0
  2. package/README.md +584 -261
  3. package/package.json +43 -47
  4. package/bin/cli.ts +0 -9
  5. package/dist/auth.d.ts +0 -134
  6. package/dist/cache/lru-cache.d.ts +0 -139
  7. package/dist/cache/middleware-memoization.d.ts +0 -151
  8. package/dist/cache/route-cache-warmer.d.ts +0 -161
  9. package/dist/cache/sqlite-cache.d.ts +0 -209
  10. package/dist/cache/streaming-cache.d.ts +0 -132
  11. package/dist/chunk-1mvtv6jw.js +0 -13012
  12. package/dist/cli/colors.d.ts +0 -15
  13. package/dist/cli/index.d.ts +0 -10
  14. package/dist/cli/middleware.d.ts +0 -31
  15. package/dist/cli/openapi.d.ts +0 -17
  16. package/dist/cli/router.d.ts +0 -15
  17. package/dist/cli/routes.d.ts +0 -29
  18. package/dist/cli/utils.d.ts +0 -74
  19. package/dist/cli.d.ts +0 -1
  20. package/dist/cli.js +0 -3195
  21. package/dist/config.d.ts +0 -7
  22. package/dist/container/container.d.ts +0 -273
  23. package/dist/container/contextual-binding.d.ts +0 -240
  24. package/dist/container/decorators.d.ts +0 -141
  25. package/dist/container/service-provider.d.ts +0 -285
  26. package/dist/development/hot-reload.d.ts +0 -187
  27. package/dist/development/index.d.ts +0 -167
  28. package/dist/development/performance-profiler.d.ts +0 -217
  29. package/dist/development/route-debugger.d.ts +0 -154
  30. package/dist/development/route-inspector.d.ts +0 -211
  31. package/dist/development/typescript-utilities.d.ts +0 -209
  32. package/dist/docs.d.ts +0 -11
  33. package/dist/errors/circuit-breaker.d.ts +0 -195
  34. package/dist/errors/error-handler.d.ts +0 -88
  35. package/dist/errors/error-reporting.d.ts +0 -144
  36. package/dist/errors/exceptions.d.ts +0 -184
  37. package/dist/errors/graceful-degradation.d.ts +0 -154
  38. package/dist/errors/index.d.ts +0 -9
  39. package/dist/errors/router-errors.d.ts +0 -110
  40. package/dist/file-serving/static-files.d.ts +0 -143
  41. package/dist/index.d.ts +0 -14
  42. package/dist/index.js +0 -13933
  43. package/dist/middleware/auth.d.ts +0 -63
  44. package/dist/middleware/content_security_policy.d.ts +0 -53
  45. package/dist/middleware/cors.d.ts +0 -5
  46. package/dist/middleware/csrf.d.ts +0 -7
  47. package/dist/middleware/ddos_protection.d.ts +0 -39
  48. package/dist/middleware/file_security.d.ts +0 -26
  49. package/dist/middleware/file_upload.d.ts +0 -38
  50. package/dist/middleware/helmet.d.ts +0 -54
  51. package/dist/middleware/index.d.ts +0 -44
  52. package/dist/middleware/input_validation.d.ts +0 -45
  53. package/dist/middleware/json_body.d.ts +0 -4
  54. package/dist/middleware/performance_alerting.d.ts +0 -87
  55. package/dist/middleware/performance_dashboard.d.ts +0 -87
  56. package/dist/middleware/performance_monitor.d.ts +0 -209
  57. package/dist/middleware/pipeline.d.ts +0 -131
  58. package/dist/middleware/rate_limit.d.ts +0 -36
  59. package/dist/middleware/request_id.d.ts +0 -4
  60. package/dist/middleware/request_signing.d.ts +0 -153
  61. package/dist/middleware/request_tracer.d.ts +0 -72
  62. package/dist/middleware/response_cache.d.ts +0 -97
  63. package/dist/middleware/security.d.ts +0 -69
  64. package/dist/middleware/security_suite.d.ts +0 -46
  65. package/dist/middleware/session.d.ts +0 -23
  66. package/dist/model-binding/index.d.ts +0 -2
  67. package/dist/model-binding/model-middleware.d.ts +0 -118
  68. package/dist/model-binding/model-registry.d.ts +0 -164
  69. package/dist/model-binding.d.ts +0 -185
  70. package/dist/model-resolver-factory.d.ts +0 -31
  71. package/dist/observability/correlation.d.ts +0 -187
  72. package/dist/observability/health-checks.d.ts +0 -186
  73. package/dist/observability/index.d.ts +0 -60
  74. package/dist/observability/integration.d.ts +0 -147
  75. package/dist/observability/metrics.d.ts +0 -184
  76. package/dist/observability/tracing.d.ts +0 -187
  77. package/dist/optimization/bun-utilities.d.ts +0 -224
  78. package/dist/query-builder-integration.d.ts +0 -36
  79. package/dist/request/context.d.ts +0 -34
  80. package/dist/request/enhanced-request.d.ts +0 -213
  81. package/dist/request/macros.d.ts +0 -300
  82. package/dist/response/macros.d.ts +0 -245
  83. package/dist/response/response-factory.d.ts +0 -133
  84. package/dist/router/api-routes.d.ts +0 -5
  85. package/dist/router/file-based-routing.d.ts +0 -118
  86. package/dist/router/file-streaming.d.ts +0 -5
  87. package/dist/router/fluent-router.d.ts +0 -315
  88. package/dist/router/fluent-routing.d.ts +0 -271
  89. package/dist/router/group-organization.d.ts +0 -5
  90. package/dist/router/handler-resolver.d.ts +0 -24
  91. package/dist/router/http-methods.d.ts +0 -10
  92. package/dist/router/index.d.ts +0 -114
  93. package/dist/router/middleware-groups.d.ts +0 -94
  94. package/dist/router/middleware-integration.d.ts +0 -112
  95. package/dist/router/middleware.d.ts +0 -5
  96. package/dist/router/model-binding.d.ts +0 -5
  97. package/dist/router/optimized-route-matching.d.ts +0 -6
  98. package/dist/router/route-building.d.ts +0 -5
  99. package/dist/router/route-compiler.d.ts +0 -153
  100. package/dist/router/route-matching.d.ts +0 -5
  101. package/dist/router/route-trie.d.ts +0 -114
  102. package/dist/router/router.d.ts +0 -294
  103. package/dist/router/server.d.ts +0 -5
  104. package/dist/router/validation-integration.d.ts +0 -170
  105. package/dist/router/view-rendering.d.ts +0 -5
  106. package/dist/router/websocket.d.ts +0 -5
  107. package/dist/routing/route-caching.d.ts +0 -129
  108. package/dist/routing/route-throttling.d.ts +0 -150
  109. package/dist/routing/subdomain-routing.d.ts +0 -206
  110. package/dist/session/database-store.d.ts +0 -51
  111. package/dist/session/file-store.d.ts +0 -22
  112. package/dist/session/index.d.ts +0 -106
  113. package/dist/session/memory-store.d.ts +0 -21
  114. package/dist/session/redis-store.d.ts +0 -31
  115. package/dist/streaming/index.d.ts +0 -3
  116. package/dist/streaming/sse-handler.d.ts +0 -138
  117. package/dist/streaming/stream-handler.d.ts +0 -114
  118. package/dist/testing/auth-testing.d.ts +0 -156
  119. package/dist/testing/file-upload-testing.d.ts +0 -190
  120. package/dist/testing/index.d.ts +0 -10
  121. package/dist/testing/middleware-testing.d.ts +0 -138
  122. package/dist/testing/model-binding-testing.d.ts +0 -186
  123. package/dist/testing/performance-testing.d.ts +0 -235
  124. package/dist/testing/test-client.d.ts +0 -117
  125. package/dist/testing/test-request.d.ts +0 -85
  126. package/dist/testing/test-response.d.ts +0 -90
  127. package/dist/testing/types.d.ts +0 -207
  128. package/dist/testing/websocket-testing.d.ts +0 -227
  129. package/dist/types/controller-types.d.ts +0 -208
  130. package/dist/types/core.d.ts +0 -543
  131. package/dist/types/middleware-types.d.ts +0 -227
  132. package/dist/types/request-response-augmentation.d.ts +0 -261
  133. package/dist/types/route-inference.d.ts +0 -168
  134. package/dist/types.d.ts +0 -1782
  135. package/dist/url.d.ts +0 -56
  136. package/dist/utils/index.d.ts +0 -1
  137. package/dist/utils/query-preservation.d.ts +0 -48
  138. package/dist/utils.d.ts +0 -69
  139. package/dist/validation/validator.d.ts +0 -140
  140. package/dist/websocket/clustering.d.ts +0 -185
  141. package/src/auth.ts +0 -469
  142. package/src/cache/lru-cache.ts +0 -457
  143. package/src/cache/middleware-memoization.ts +0 -531
  144. package/src/cache/route-cache-warmer.ts +0 -486
  145. package/src/cache/sqlite-cache.ts +0 -783
  146. package/src/cache/streaming-cache.ts +0 -572
  147. package/src/cli/colors.ts +0 -29
  148. package/src/cli/index.ts +0 -287
  149. package/src/cli/middleware.ts +0 -291
  150. package/src/cli/openapi.ts +0 -407
  151. package/src/cli/router.ts +0 -188
  152. package/src/cli/routes.ts +0 -265
  153. package/src/cli/utils.ts +0 -531
  154. package/src/cli.ts +0 -5
  155. package/src/config.ts +0 -322
  156. package/src/container/container.ts +0 -740
  157. package/src/container/contextual-binding.ts +0 -603
  158. package/src/container/decorators.ts +0 -359
  159. package/src/container/service-provider.ts +0 -596
  160. package/src/development/hot-reload.ts +0 -673
  161. package/src/development/index.ts +0 -499
  162. package/src/development/performance-profiler.ts +0 -717
  163. package/src/development/route-debugger.ts +0 -527
  164. package/src/development/route-inspector.ts +0 -749
  165. package/src/development/typescript-utilities.ts +0 -682
  166. package/src/docs.ts +0 -397
  167. package/src/errors/circuit-breaker.ts +0 -732
  168. package/src/errors/error-handler.ts +0 -569
  169. package/src/errors/error-reporting.ts +0 -672
  170. package/src/errors/exceptions.ts +0 -536
  171. package/src/errors/graceful-degradation.ts +0 -621
  172. package/src/errors/index.ts +0 -21
  173. package/src/errors/router-errors.ts +0 -632
  174. package/src/file-serving/static-files.ts +0 -581
  175. package/src/index.ts +0 -14
  176. package/src/middleware/auth.ts +0 -219
  177. package/src/middleware/content_security_policy.ts +0 -215
  178. package/src/middleware/cors.ts +0 -74
  179. package/src/middleware/csrf.ts +0 -108
  180. package/src/middleware/ddos_protection.ts +0 -255
  181. package/src/middleware/file_security.ts +0 -191
  182. package/src/middleware/file_upload.ts +0 -264
  183. package/src/middleware/helmet.ts +0 -268
  184. package/src/middleware/index.ts +0 -117
  185. package/src/middleware/input_validation.ts +0 -449
  186. package/src/middleware/json_body.ts +0 -37
  187. package/src/middleware/performance_alerting.ts +0 -538
  188. package/src/middleware/performance_dashboard.ts +0 -661
  189. package/src/middleware/performance_monitor.ts +0 -943
  190. package/src/middleware/pipeline.ts +0 -489
  191. package/src/middleware/rate_limit.ts +0 -245
  192. package/src/middleware/request_id.ts +0 -36
  193. package/src/middleware/request_signing.ts +0 -636
  194. package/src/middleware/request_tracer.ts +0 -636
  195. package/src/middleware/response_cache.ts +0 -743
  196. package/src/middleware/security.ts +0 -482
  197. package/src/middleware/security_suite.ts +0 -257
  198. package/src/middleware/session.ts +0 -91
  199. package/src/model-binding/index.ts +0 -18
  200. package/src/model-binding/model-middleware.ts +0 -425
  201. package/src/model-binding/model-registry.ts +0 -550
  202. package/src/model-binding.ts +0 -370
  203. package/src/model-resolver-factory.ts +0 -106
  204. package/src/observability/correlation.ts +0 -691
  205. package/src/observability/health-checks.ts +0 -729
  206. package/src/observability/index.ts +0 -184
  207. package/src/observability/integration.ts +0 -548
  208. package/src/observability/metrics.ts +0 -753
  209. package/src/observability/tracing.ts +0 -638
  210. package/src/optimization/bun-utilities.ts +0 -778
  211. package/src/query-builder-integration.ts +0 -137
  212. package/src/request/context.ts +0 -62
  213. package/src/request/enhanced-request.ts +0 -857
  214. package/src/request/macros.ts +0 -688
  215. package/src/response/macros.ts +0 -612
  216. package/src/response/response-factory.ts +0 -596
  217. package/src/router/api-routes.ts +0 -243
  218. package/src/router/file-based-routing.ts +0 -670
  219. package/src/router/file-streaming.ts +0 -372
  220. package/src/router/fluent-router.ts +0 -927
  221. package/src/router/fluent-routing.ts +0 -797
  222. package/src/router/group-organization.ts +0 -213
  223. package/src/router/handler-resolver.ts +0 -291
  224. package/src/router/http-methods.ts +0 -377
  225. package/src/router/index.ts +0 -187
  226. package/src/router/middleware-groups.ts +0 -222
  227. package/src/router/middleware-integration.ts +0 -399
  228. package/src/router/middleware.ts +0 -231
  229. package/src/router/model-binding.ts +0 -215
  230. package/src/router/optimized-route-matching.ts +0 -253
  231. package/src/router/route-building.ts +0 -212
  232. package/src/router/route-compiler.ts +0 -702
  233. package/src/router/route-matching.ts +0 -349
  234. package/src/router/route-trie.ts +0 -464
  235. package/src/router/router.ts +0 -1581
  236. package/src/router/server.ts +0 -462
  237. package/src/router/validation-integration.ts +0 -443
  238. package/src/router/view-rendering.ts +0 -233
  239. package/src/router/websocket.ts +0 -100
  240. package/src/routing/route-caching.ts +0 -402
  241. package/src/routing/route-throttling.ts +0 -469
  242. package/src/routing/subdomain-routing.ts +0 -492
  243. package/src/session/database-store.ts +0 -109
  244. package/src/session/file-store.ts +0 -148
  245. package/src/session/index.ts +0 -244
  246. package/src/session/memory-store.ts +0 -88
  247. package/src/session/redis-store.ts +0 -93
  248. package/src/streaming/index.ts +0 -17
  249. package/src/streaming/sse-handler.ts +0 -482
  250. package/src/streaming/stream-handler.ts +0 -552
  251. package/src/testing/auth-testing.ts +0 -446
  252. package/src/testing/file-upload-testing.ts +0 -543
  253. package/src/testing/index.ts +0 -10
  254. package/src/testing/middleware-testing.ts +0 -322
  255. package/src/testing/model-binding-testing.ts +0 -645
  256. package/src/testing/performance-testing.ts +0 -738
  257. package/src/testing/test-client.ts +0 -310
  258. package/src/testing/test-request.ts +0 -315
  259. package/src/testing/test-response.ts +0 -332
  260. package/src/testing/types.ts +0 -224
  261. package/src/testing/websocket-testing.ts +0 -590
  262. package/src/types/controller-types.ts +0 -385
  263. package/src/types/core.ts +0 -683
  264. package/src/types/middleware-types.ts +0 -419
  265. package/src/types/request-response-augmentation.ts +0 -489
  266. package/src/types/route-inference.ts +0 -357
  267. package/src/types.ts +0 -2055
  268. package/src/url.ts +0 -126
  269. package/src/utils/index.ts +0 -1
  270. package/src/utils/query-preservation.ts +0 -201
  271. package/src/utils.ts +0 -327
  272. package/src/validation/validator.ts +0 -685
  273. package/src/websocket/clustering.ts +0 -762
package/src/types.ts DELETED
@@ -1,2055 +0,0 @@
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
- * Lookup a single route param. Equivalent to `request.params[name]` but
798
- * with optional default-value handling, matching the Laravel-style
799
- * `$request->route('name')` ergonomics.
800
- */
801
- getParam: <T = string>(name: string, defaultValue?: T) => T | undefined
802
- /**
803
- * Query parameters from the URL
804
- */
805
- query: Record<string, string | string[]>
806
- /**
807
- * Parsed JSON body (if Content-Type is application/json)
808
- */
809
- jsonBody?: Record<string, unknown>
810
- /**
811
- * Form body data (if Content-Type is multipart/form-data or application/x-www-form-urlencoded)
812
- */
813
- formBody?: FormBody
814
- /**
815
- * Uploaded files (if Content-Type is multipart/form-data)
816
- */
817
- files?: UploadedFile[]
818
- /**
819
- * Session data (if session middleware is used)
820
- */
821
- session?: SessionData
822
- /**
823
- * User data (if authentication middleware is used)
824
- */
825
- user?: User
826
- /**
827
- * Additional context data that can be set by middleware
828
- */
829
- context?: RequestContext
830
- /**
831
- * Validated data from validation middleware
832
- */
833
- validated?: ValidatedData
834
- /**
835
- * Model binding data
836
- */
837
- models?: BoundModels
838
- /**
839
- * Model binding errors
840
- */
841
- modelErrors?: Record<string, string>
842
- /**
843
- * Authenticated user from auth middleware
844
- */
845
- auth?: AuthContext
846
- /**
847
- * Rate limiting information
848
- */
849
- rateLimitRemaining?: number
850
- /**
851
- * Request ID for tracing
852
- */
853
- requestId?: string
854
- /**
855
- * IP address of the client (string property, not function from RequestMacroMethods)
856
- */
857
- ip?: string
858
- /**
859
- * Cookies parsed from the request with utility methods
860
- */
861
- cookies?: CookieAccessor
862
- /**
863
- * Flash messages (temporary messages for the next request)
864
- */
865
- flash?: FlashMessages
866
- /**
867
- * CSRF token
868
- */
869
- csrfToken?: string
870
- /**
871
- * Request start time for performance monitoring
872
- */
873
- startTime?: number
874
- /**
875
- * Trace ID for distributed tracing
876
- */
877
- traceId?: string
878
- /**
879
- * Span ID for distributed tracing
880
- */
881
- spanId?: string
882
- /**
883
- * Security middleware additions
884
- */
885
- nonce?: string
886
- validatedBody?: ValidatedBody
887
- /**
888
- * Internal cookies to set in response (used by cookie utilities)
889
- */
890
- _cookiesToSet?: CookieToSet[]
891
- /**
892
- * Internal cookies to delete in response (used by cookie utilities)
893
- */
894
- _cookiesToDelete?: CookieToDelete[]
895
- /**
896
- * SSE connection information
897
- */
898
- sse?: SSEConnection
899
- /**
900
- * The matched route object
901
- */
902
- route?: Route
903
- }
904
-
905
- export interface UploadedFile {
906
- fieldName: string
907
- originalName: string
908
- filename: string
909
- path: string
910
- size: number
911
- mimetype: string
912
- buffer: ArrayBuffer
913
- }
914
-
915
- export type RouteHandler = (_req: EnhancedRequest) => Response | Promise<Response>
916
-
917
- /**
918
- * Interface for handling route actions.
919
- * All action handlers must implement this interface.
920
- */
921
- export interface ActionHandlerClass {
922
- /**
923
- * Handles an incoming HTTP request and returns a response.
924
- * @param request The incoming HTTP request
925
- * @returns A Promise that resolves to a Response object
926
- */
927
- handle: (request: EnhancedRequest) => Promise<Response>
928
- }
929
-
930
- /**
931
- * Action handler path with strict pattern validation
932
- */
933
- export type ActionPath = `Actions/${string}Action` | `actions/${string}Action` | `${string}Controller@${string}`
934
-
935
- /**
936
- * Strongly typed action handler with better type safety
937
- */
938
- export type ActionHandler<TPath extends string = string> =
939
- | ActionPath
940
- | TypedRouteHandler<TPath>
941
- | RouteHandler
942
- | (new () => ActionHandlerClass)
943
- | Response
944
-
945
- /**
946
- * Controller method reference with strict typing
947
- */
948
- export type ControllerMethod<
949
- TController extends string = string,
950
- TMethod extends string = string,
951
- > = `${TController}@${TMethod}`
952
-
953
- /**
954
- * Action class constructor with typed handle method
955
- */
956
- export interface TypedActionHandlerClass<TPath extends string = string> {
957
- handle: (request: EnhancedRequest & { params: ExtractRouteParams<TPath> }) => Promise<Response>
958
- }
959
-
960
- /**
961
- * Discriminated union for different action handler types
962
- */
963
- export type ActionHandlerVariant<TPath extends string = string> =
964
- | { type: 'path', value: ActionPath }
965
- | { type: 'function', value: TypedRouteHandler<TPath> }
966
- | { type: 'class', value: new () => TypedActionHandlerClass<TPath> }
967
- | { type: 'controller', value: ControllerMethod }
968
-
969
- export type NextFunction = () => Promise<Response | null> | Response | null
970
- export type MiddlewareHandler = (_req: EnhancedRequest, _next: NextFunction) => Promise<Response | null> | Response | null
971
-
972
- export interface Middleware {
973
- handle: MiddlewareHandler
974
- }
975
-
976
- /**
977
- * Strict middleware configuration with narrow types
978
- */
979
- export interface StrictMiddlewareConfig {
980
- name: BuiltInMiddleware
981
- enabled: boolean
982
- priority: number
983
- timing: MiddlewareTiming
984
- params?: Record<string, string | number | boolean>
985
- }
986
-
987
- /**
988
- * Conditional middleware with narrow type constraints
989
- */
990
- export interface ConditionalMiddleware<T extends BuiltInMiddleware = BuiltInMiddleware> {
991
- name: T
992
- condition: (req: EnhancedRequest) => boolean
993
- handler: MiddlewareHandler
994
- priority?: number
995
- }
996
-
997
- /**
998
- * Middleware group configuration with strict typing
999
- */
1000
- export interface MiddlewareGroup {
1001
- name: string
1002
- middleware: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware>)[]
1003
- priority: number
1004
- description?: string
1005
- }
1006
-
1007
- /**
1008
- * Throttle middleware parameters with narrow types
1009
- */
1010
- export interface ThrottleMiddlewareParams {
1011
- pattern: ThrottlePattern
1012
- name?: string
1013
- keyGenerator?: (req: EnhancedRequest) => string
1014
- skipIf?: (req: EnhancedRequest) => boolean
1015
- }
1016
-
1017
- /**
1018
- * CORS middleware configuration with strict options
1019
- */
1020
- export interface CorsMiddlewareConfig {
1021
- origin: string | string[] | boolean | ((_origin: string) => boolean)
1022
- methods: HTTPMethod[]
1023
- allowedHeaders: string[]
1024
- exposedHeaders?: string[]
1025
- credentials: boolean
1026
- maxAge: number
1027
- preflightContinue: boolean
1028
- optionsSuccessStatus: ResponseStatus
1029
- }
1030
-
1031
- /**
1032
- * Auth middleware configuration with narrow types
1033
- */
1034
- export interface AuthMiddlewareConfig {
1035
- type: 'jwt' | 'session' | 'apikey' | 'basic' | 'bearer'
1036
- required: boolean
1037
- realm?: string
1038
- validateUser?: (user: User) => boolean
1039
- onUnauthorized?: (req: EnhancedRequest) => Response
1040
- }
1041
-
1042
- export interface RouteGroup {
1043
- prefix?: string
1044
- middleware?: (string | MiddlewareHandler)[]
1045
- }
1046
-
1047
- export interface Route {
1048
- path: string
1049
- handler: ActionHandler
1050
- method: string
1051
- middleware: MiddlewareHandler[]
1052
- type?: 'api' | 'web'
1053
- name?: string
1054
- constraints?: Record<string, string> | ((_params: Record<string, string>) => boolean)[]
1055
- domain?: string
1056
- params?: Record<string, string>
1057
- pattern?: {
1058
- exec: (url: URL) => PatternMatchResult | null
1059
- }
1060
- }
1061
-
1062
- /**
1063
- * WebSocket handler configuration
1064
- */
1065
- export interface WebSocketConfig<T extends WebSocketData = WebSocketData> {
1066
- open?: (ws: TypedServerWebSocket<T>) => void | Promise<void>
1067
- message: (ws: TypedServerWebSocket<T>, message: string | Uint8Array | ArrayBuffer) => void | Promise<void>
1068
- close?: (ws: TypedServerWebSocket<T>, code: number, reason: string) => void | Promise<void>
1069
- ping?: (ws: TypedServerWebSocket<T>, data: Uint8Array) => void | Promise<void>
1070
- pong?: (ws: TypedServerWebSocket<T>, data: Uint8Array) => void | Promise<void>
1071
- drain?: (ws: TypedServerWebSocket<T>) => void | Promise<void>
1072
- error?: (ws: TypedServerWebSocket<T>, error: Error) => void | Promise<void>
1073
- maxPayloadLength?: number
1074
- backpressureLimit?: number
1075
- closeOnBackpressureLimit?: boolean
1076
- idleTimeout?: number
1077
- perMessageDeflate?: boolean | {
1078
- compress?: boolean | Compressor
1079
- decompress?: boolean | Compressor
1080
- }
1081
- sendPings?: boolean
1082
- publishToSelf?: boolean
1083
- }
1084
-
1085
- export type Compressor =
1086
- | 'disable'
1087
- | 'shared'
1088
- | 'dedicated'
1089
- | '3KB'
1090
- | '4KB'
1091
- | '8KB'
1092
- | '16KB'
1093
- | '32KB'
1094
- | '64KB'
1095
- | '128KB'
1096
- | '256KB'
1097
-
1098
- export interface ServerOptions<T extends WebSocketData = WebSocketData> extends Partial<Omit<Server<T>, 'websocket' | 'development'>> {
1099
- websocket?: WebSocketConfig<T>
1100
- /**
1101
- * Pre-computed static responses served by Bun's native static dispatch.
1102
- * These bypass the fetch handler entirely for zero-allocation serving (~15% faster).
1103
- */
1104
- static?: Record<string, Response>
1105
- /**
1106
- * Development mode options for Bun's dev server.
1107
- * When true, enables HMR and development features.
1108
- * When an object, allows fine-grained control over HMR and console streaming.
1109
- *
1110
- * @example
1111
- * // Stream browser console.log/console.error to terminal
1112
- * development: { console: true }
1113
- *
1114
- * // Enable HMR + console streaming
1115
- * development: { hmr: true, console: true }
1116
- */
1117
- development?: boolean | {
1118
- hmr?: boolean
1119
- console?: boolean
1120
- }
1121
- }
1122
-
1123
- /**
1124
- * Type definition for route configuration with strict typing.
1125
- */
1126
- export interface RouteDefinition<
1127
- TPath extends string = string,
1128
- TMethod extends HTTPMethod = HTTPMethod,
1129
- THandler extends ActionHandler = ActionHandler,
1130
- > {
1131
- /**
1132
- * The path pattern for the route
1133
- */
1134
- path: TPath
1135
- /**
1136
- * The HTTP method for the route
1137
- */
1138
- method: TMethod
1139
- /**
1140
- * The action handler for the route - can be a string path, function, or class
1141
- */
1142
- handler: THandler
1143
- /**
1144
- * Optional array of middleware to be executed before the handler
1145
- */
1146
- middleware?: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware> | MiddlewareHandler)[]
1147
- /**
1148
- * Optional route type to distinguish between API and web routes
1149
- */
1150
- type?: 'api' | 'web'
1151
- /**
1152
- * Optional route name for reverse routing
1153
- */
1154
- name?: string
1155
- /**
1156
- * Route parameter constraints
1157
- */
1158
- constraints?: {
1159
- [K in keyof ExtractRouteParams<TPath>]: RouteConstraint
1160
- }
1161
- /**
1162
- * Optional route metadata for documentation or other purposes
1163
- */
1164
- meta?: RouteMetadata
1165
- /**
1166
- * Cache configuration for this specific route
1167
- */
1168
- cache?: {
1169
- enabled: boolean
1170
- ttl: number
1171
- tags?: string[]
1172
- strategy?: CacheStrategy
1173
- }
1174
- /**
1175
- * Rate limiting configuration for this route
1176
- */
1177
- throttle?: ThrottlePattern | ThrottleMiddlewareParams
1178
- }
1179
-
1180
- /**
1181
- * HTTP Methods type - extremely narrow
1182
- */
1183
- export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' | 'TRACE' | 'CONNECT'
1184
-
1185
- /**
1186
- * Narrow throttle pattern types
1187
- */
1188
- export type ThrottlePattern =
1189
- | `${number}` // e.g., "60" (60 requests per 1 minute)
1190
- | `${number},${number}` // e.g., "60,1" (60 requests per 1 minute)
1191
- | `${number},${number}min` // e.g., "60,5min" (60 requests per 5 minutes)
1192
- | `${number},${number}m` // e.g., "60,5m" (60 requests per 5 minutes)
1193
- | `${number},${number}sec` // e.g., "100,30sec" (100 requests per 30 seconds)
1194
- | `${number},${number}s` // e.g., "100,30s" (100 requests per 30 seconds)
1195
- | `${number},${number}hour` // e.g., "1000,1hour" (1000 requests per 1 hour)
1196
- | `${number},${number}h` // e.g., "1000,1h" (1000 requests per 1 hour)
1197
-
1198
- /**
1199
- * Cache strategy types - narrow and specific
1200
- */
1201
- export type CacheStrategy = 'stale-while-revalidate' | 'cache-first' | 'network-first'
1202
-
1203
- /**
1204
- * Cache type narrow definition
1205
- */
1206
- export type CacheType = 'memory' | 'redis' | 'custom'
1207
-
1208
- /**
1209
- * File extension types for views
1210
- */
1211
- export type ViewExtension = '.html' | '.stx' | '.hbs' | '.ejs' | '.pug' | '.mustache'
1212
-
1213
- /**
1214
- * Template engine types
1215
- */
1216
- export type TemplateEngine = 'auto' | 'stx' | 'html' | 'handlebars' | 'ejs' | 'pug' | 'mustache' | 'custom'
1217
-
1218
- /**
1219
- * Route parameter constraint patterns
1220
- */
1221
- export type RouteConstraint =
1222
- | 'number' // Only numbers
1223
- | 'alpha' // Only letters
1224
- | 'alphanumeric' // Letters and numbers
1225
- | 'uuid' // UUID format
1226
- | 'slug' // URL-friendly slug
1227
- | RegExp // Custom regex
1228
- | string // Custom pattern string
1229
-
1230
- /**
1231
- * Middleware execution timing
1232
- */
1233
- export type MiddlewareTiming = 'before' | 'after' | 'around'
1234
-
1235
- /**
1236
- * Security header types
1237
- */
1238
- export type SecurityHeader =
1239
- | 'Content-Security-Policy'
1240
- | 'X-Frame-Options'
1241
- | 'X-Content-Type-Options'
1242
- | 'Referrer-Policy'
1243
- | 'Permissions-Policy'
1244
- | 'Strict-Transport-Security'
1245
-
1246
- /**
1247
- * Built-in middleware names - extremely narrow
1248
- */
1249
- export type BuiltInMiddleware =
1250
- | 'auth'
1251
- | 'cors'
1252
- | 'csrf'
1253
- | 'helmet'
1254
- | 'json'
1255
- | 'compress'
1256
- | 'static'
1257
- | 'session'
1258
- | 'rateLimiter'
1259
- | 'requestId'
1260
- | 'logger'
1261
- | 'throttle'
1262
-
1263
- /**
1264
- * Middleware with parameters
1265
- */
1266
- export type MiddlewareWithParams<T extends string = string> =
1267
- | T
1268
- | `${T}:${string}`
1269
-
1270
- /**
1271
- * Route path parameter types - narrow template literals
1272
- */
1273
- export type RouteParam<T extends string> = T extends `{${infer P}}` ? P : never
1274
-
1275
- /**
1276
- * Extract parameters from route path
1277
- */
1278
- export type ExtractRouteParams<T extends string> =
1279
- T extends `${string}{${infer Param}}${infer Rest}`
1280
- ? { [K in Param]: string } & ExtractRouteParams<Rest>
1281
- : object
1282
-
1283
- /**
1284
- * Route method constraints
1285
- */
1286
- export type RouteMethodConstraint<M extends HTTPMethod = HTTPMethod> = M
1287
-
1288
- /**
1289
- * File MIME types for uploads
1290
- */
1291
- export type AllowedMimeType =
1292
- | 'image/jpeg'
1293
- | 'image/png'
1294
- | 'image/gif'
1295
- | 'image/webp'
1296
- | 'image/svg+xml'
1297
- | 'application/pdf'
1298
- | 'application/json'
1299
- | 'text/plain'
1300
- | 'text/csv'
1301
- | 'application/octet-stream'
1302
-
1303
- /**
1304
- * Response status codes - narrow and specific
1305
- */
1306
- export type ResponseStatus =
1307
- | 200 | 201 | 202 | 204 // Success
1308
- | 301 | 302 | 304 // Redirects
1309
- | 400 | 401 | 403 | 404 | 405 | 409 | 422 | 429 // Client errors
1310
- | 500 | 502 | 503 | 504 // Server errors
1311
-
1312
- /**
1313
- * Content types - narrow
1314
- */
1315
- export type ContentType =
1316
- | 'application/json'
1317
- | 'application/xml'
1318
- | 'text/html'
1319
- | 'text/plain'
1320
- | 'text/csv'
1321
- | 'application/pdf'
1322
- | 'application/octet-stream'
1323
- | 'multipart/form-data'
1324
- | 'application/x-www-form-urlencoded'
1325
-
1326
- /**
1327
- * Strongly typed route method signatures
1328
- */
1329
- export interface TypedRouteHandler<TPath extends string> {
1330
- (req: EnhancedRequest & { params: ExtractRouteParams<TPath> }): Response | Promise<Response>
1331
- }
1332
-
1333
- /**
1334
- * Strongly typed route definition for specific HTTP methods
1335
- */
1336
- export interface GetRoute<TPath extends string> extends RouteDefinition<TPath, 'GET'> {
1337
- method: 'GET'
1338
- handler: TypedRouteHandler<TPath> | ActionHandler
1339
- }
1340
-
1341
- export interface PostRoute<TPath extends string> extends RouteDefinition<TPath, 'POST'> {
1342
- method: 'POST'
1343
- handler: TypedRouteHandler<TPath> | ActionHandler
1344
- }
1345
-
1346
- export interface PutRoute<TPath extends string> extends RouteDefinition<TPath, 'PUT'> {
1347
- method: 'PUT'
1348
- handler: TypedRouteHandler<TPath> | ActionHandler
1349
- }
1350
-
1351
- export interface DeleteRoute<TPath extends string> extends RouteDefinition<TPath, 'DELETE'> {
1352
- method: 'DELETE'
1353
- handler: TypedRouteHandler<TPath> | ActionHandler
1354
- }
1355
-
1356
- export interface PatchRoute<TPath extends string> extends RouteDefinition<TPath, 'PATCH'> {
1357
- method: 'PATCH'
1358
- handler: TypedRouteHandler<TPath> | ActionHandler
1359
- }
1360
-
1361
- /**
1362
- * Union of all typed route definitions
1363
- */
1364
- export type TypedRouteDefinition<TPath extends string = string> =
1365
- | GetRoute<TPath>
1366
- | PostRoute<TPath>
1367
- | PutRoute<TPath>
1368
- | DeleteRoute<TPath>
1369
- | PatchRoute<TPath>
1370
-
1371
- /**
1372
- * Route validation helpers
1373
- */
1374
- export interface RouteValidation<TPath extends string> {
1375
- path: TPath
1376
- params: ExtractRouteParams<TPath>
1377
- validate: (req: EnhancedRequest) => req is EnhancedRequest & { params: ExtractRouteParams<TPath> }
1378
- }
1379
-
1380
- /**
1381
- * Common route patterns with strict template literal types
1382
- */
1383
- export type CommonRoutePatterns =
1384
- | '/' // Root
1385
- | '/health' // Health check
1386
- | '/api' // API root
1387
- | '/api/v1' // Versioned API
1388
- | '/api/v1/users' // User collection
1389
- | '/api/v1/users/{id}' // User resource
1390
- | '/api/v1/users/{userId}/posts' // Nested resource
1391
- | '/api/v1/users/{userId}/posts/{postId}' // Nested resource item
1392
- | '/admin' // Admin panel
1393
- | '/admin/{section}' // Admin section
1394
- | '/auth/login' // Authentication
1395
- | '/auth/logout' // Logout
1396
- | '/auth/register' // Registration
1397
- | '/auth/forgot-password' // Password reset
1398
- | '/uploads/{filename}' // File uploads
1399
- | '/assets/{path}' // Static assets
1400
-
1401
- /**
1402
- * RESTful resource route patterns
1403
- */
1404
- export type ResourceRoutePatterns<T extends string> =
1405
- | `/${T}` // Collection: GET /users
1406
- | `/${T}/{id}` // Item: GET /users/123
1407
- | `/${T}/create` // Create form: GET /users/create
1408
- | `/${T}/{id}/edit` // Edit form: GET /users/123/edit
1409
- | `/${T}/{id}/show` // Show item: GET /users/123/show
1410
-
1411
- /**
1412
- * API versioning patterns
1413
- */
1414
- export type ApiVersionPattern<V extends string, Path extends string> = `/api/${V}${Path}`
1415
-
1416
- /**
1417
- * Nested resource patterns
1418
- */
1419
- export type NestedResourcePattern<
1420
- Parent extends string,
1421
- Child extends string,
1422
- ParentId extends string = 'id',
1423
- ChildId extends string = 'id',
1424
- > = `/${Parent}/{${ParentId}}/${Child}` | `/${Parent}/{${ParentId}}/${Child}/{${ChildId}}`
1425
-
1426
- /**
1427
- * Route parameter patterns with constraints
1428
- */
1429
- export type IdPattern = '{id}'
1430
- export type UuidPattern = '{uuid}'
1431
- export type SlugPattern = '{slug}'
1432
- export type NumberPattern = '{number}'
1433
-
1434
- /**
1435
- * File path patterns
1436
- */
1437
- export type FilePathPattern = '{filepath}' | '{*filepath}' | '{path...}'
1438
-
1439
- /**
1440
- * Discriminated union for cache configurations
1441
- */
1442
- export type CacheConfigVariant =
1443
- | { type: 'memory', maxSize: number, ttl: number }
1444
- | { type: 'redis', url: string, prefix: string, ttl: number, maxRetries: number }
1445
- | { type: 'custom', adapter: CacheConfig['customAdapter'], ttl: number }
1446
-
1447
- /**
1448
- * Discriminated union for authentication configurations
1449
- */
1450
- export type AuthConfigVariant =
1451
- | { type: 'jwt', secret: string, expiresIn: string, algorithm: 'HS256' | 'HS384' | 'HS512' | 'RS256' }
1452
- | { type: 'session', secret: string, store: CacheType, maxAge: number }
1453
- | { type: 'apikey', keyName: string, location: 'header' | 'query' | 'cookie' }
1454
- | { type: 'basic', realm: string, users: Record<string, string> }
1455
- | { type: 'bearer', validate: (token: string) => Promise<boolean> }
1456
-
1457
- /**
1458
- * Discriminated union for rate limiting configurations
1459
- */
1460
- export type RateLimitConfigVariant =
1461
- | { type: 'memory', maxAttempts: number, windowMs: number, keyGenerator?: (req: EnhancedRequest) => string }
1462
- | { type: 'redis', maxAttempts: number, windowMs: number, redisUrl: string, keyPrefix: string }
1463
- | { type: 'pattern', pattern: ThrottlePattern, name?: string }
1464
-
1465
- /**
1466
- * Discriminated union for middleware configurations
1467
- */
1468
- export type MiddlewareConfigVariant =
1469
- | { type: 'throttle', config: RateLimitConfigVariant }
1470
- | { type: 'cors', config: CorsMiddlewareConfig }
1471
- | { type: 'auth', config: AuthConfigVariant }
1472
- | { type: 'cache', config: CacheConfigVariant }
1473
- | { type: 'custom', name: string, handler: MiddlewareHandler, params?: MiddlewareParams }
1474
-
1475
- /**
1476
- * Discriminated union for route handlers
1477
- */
1478
- export type RouteHandlerVariant<TPath extends string = string> =
1479
- | { type: 'action', path: ActionPath }
1480
- | { type: 'function', handler: TypedRouteHandler<TPath> }
1481
- | { type: 'class', constructor: new () => TypedActionHandlerClass<TPath> }
1482
- | { type: 'controller', method: ControllerMethod }
1483
-
1484
- /**
1485
- * Discriminated union for validation rules
1486
- */
1487
- export type ValidationRuleVariant =
1488
- | { type: 'required', message?: string }
1489
- | { type: 'string', minLength?: number, maxLength?: number, pattern?: RegExp }
1490
- | { type: 'number', min?: number, max?: number, integer?: boolean }
1491
- | { type: 'email', message?: string }
1492
- | { type: 'url', protocols?: string[] }
1493
- | { type: 'custom', validate: (value: unknown) => boolean | Promise<boolean>, message: string }
1494
-
1495
- /**
1496
- * Streaming configuration types with extreme narrowing
1497
- */
1498
- export type StreamingFormat = 'json' | 'ndjson' | 'csv' | 'xml' | 'text' | 'binary'
1499
- export type StreamingCompression = 'gzip' | 'deflate' | 'br' | 'none'
1500
- export type StreamingMode = 'chunked' | 'buffered' | 'direct'
1501
-
1502
- /**
1503
- * Server-Sent Events configuration
1504
- */
1505
- export interface SSEConfig {
1506
- retryInterval?: number
1507
- keepAlive?: number
1508
- compression?: StreamingCompression
1509
- maxConnections?: number
1510
- heartbeatInterval?: number
1511
- headers?: Record<string, string>
1512
- enableHeartbeat?: boolean
1513
- connectionTimeout?: number
1514
- retryDelay?: number
1515
- }
1516
-
1517
- /**
1518
- * SSE Event data structure with strict typing
1519
- */
1520
- export interface SSEEvent<T = unknown> {
1521
- data: T
1522
- event?: string
1523
- id?: string | number
1524
- retry?: number
1525
- comment?: string
1526
- }
1527
-
1528
- /**
1529
- * Stream generator function types
1530
- */
1531
- export type SSEGenerator<T = unknown> = () => AsyncGenerator<SSEEvent<T>, void, unknown>
1532
-
1533
- /**
1534
- * Direct streaming configuration
1535
- */
1536
- export interface DirectStreamConfig {
1537
- headers?: Record<string, string>
1538
- status?: ResponseStatus
1539
- compression?: StreamingCompression
1540
- format?: StreamingFormat
1541
- bufferSize?: number
1542
- delimiter?: string
1543
- contentType?: ContentType
1544
- enableCompression?: boolean
1545
- compressionType?: StreamingCompression
1546
- }
1547
-
1548
- /**
1549
- * Buffered streaming configuration
1550
- */
1551
- export interface BufferedStreamConfig extends DirectStreamConfig {
1552
- highWaterMark?: number
1553
- maxBuffer?: number
1554
- flushInterval?: number
1555
- autoFlush?: boolean
1556
- contentType?: ContentType
1557
- }
1558
-
1559
- /**
1560
- * File streaming configuration with strict types
1561
- */
1562
- export interface FileStreamConfig {
1563
- headers?: Record<string, string>
1564
- status?: ResponseStatus
1565
- mimeType?: AllowedMimeType
1566
- disposition?: 'inline' | 'attachment'
1567
- filename?: string
1568
- maxAge?: number
1569
- etag?: boolean
1570
- lastModified?: boolean
1571
- compression?: StreamingCompression
1572
- }
1573
-
1574
- /**
1575
- * Range request configuration for file streaming
1576
- */
1577
- export interface RangeStreamConfig extends FileStreamConfig {
1578
- unit?: 'bytes'
1579
- maxRanges?: number
1580
- enableMultipart?: boolean
1581
- }
1582
-
1583
- /**
1584
- * Transform stream configuration
1585
- */
1586
- export interface TransformStreamConfig<TInput = any, TOutput = any> {
1587
- transform: (chunk: TInput) => TOutput | Promise<TOutput>
1588
- flush?: () => TOutput[] | Promise<TOutput[]>
1589
- objectMode?: boolean
1590
- highWaterMark?: number
1591
- format?: StreamingFormat
1592
- headers?: Record<string, string>
1593
- }
1594
-
1595
- /**
1596
- * Streaming response writer interfaces
1597
- */
1598
- export interface StreamWriter<T = any> {
1599
- write: (chunk: T) => void | Promise<void>
1600
- end: () => void | Promise<void>
1601
- close: () => void
1602
- }
1603
-
1604
- export interface BufferedStreamWriterGeneric<T = any> extends StreamWriter<T> {
1605
- flush: () => void | Promise<void>
1606
- cork: () => void
1607
- uncork: () => void
1608
- }
1609
-
1610
- /**
1611
- * Model binding configuration with strict types
1612
- */
1613
- export interface ModelBinding<T = any> {
1614
- name: string
1615
- model: string // Model name
1616
- parameter: string // Parameter name
1617
- required?: boolean
1618
- as?: string // Alias for the bound model
1619
- resolver: ModelResolver<T>
1620
- cache?: {
1621
- enabled: boolean
1622
- ttl: number
1623
- key?: (params: Record<string, string>) => string
1624
- }
1625
- validation?: {
1626
- required?: boolean
1627
- validator?: (model: T) => boolean | Promise<boolean>
1628
- }
1629
- errorHandler?: (error: Error, params: Record<string, string>) => Response
1630
- }
1631
-
1632
- /**
1633
- * Model resolver function type
1634
- */
1635
- export type ModelResolver<T = any> = (
1636
- params: Record<string, string>,
1637
- req: EnhancedRequest
1638
- ) => T | Promise<T> | null
1639
-
1640
- /**
1641
- * Model validator function type
1642
- */
1643
- export type ModelValidatorFn<T = any> = (
1644
- model: T,
1645
- params: Record<string, string>,
1646
- req?: EnhancedRequest
1647
- ) => Promise<{ valid: boolean, error?: string, status?: number }> | { valid: boolean, error?: string, status?: number }
1648
-
1649
- /**
1650
- * Model transformer function type
1651
- */
1652
- export type ModelTransformerFn<T = any> = (
1653
- model: T,
1654
- params?: Record<string, string>,
1655
- req?: EnhancedRequest
1656
- ) => any | Promise<any>
1657
-
1658
- /**
1659
- * Model registry interface
1660
- */
1661
- export interface ModelRegistry {
1662
- register: <T>(binding: ModelBinding<T>) => void
1663
- resolve: <T>(name: string, params: Record<string, string>, req: EnhancedRequest) => Promise<T | null>
1664
- has: (name: string) => boolean
1665
- clear: () => void
1666
- getAll: () => ModelBinding[]
1667
- }
1668
-
1669
- /**
1670
- * Model binding middleware configuration
1671
- */
1672
- export interface ModelBindingConfig {
1673
- parameterName: string
1674
- modelName: string
1675
- required?: boolean
1676
- cacheKey?: (params: Record<string, string>) => string
1677
- }
1678
-
1679
- /**
1680
- * Resource route configuration with model binding
1681
- */
1682
- export interface ResourceConfig {
1683
- controller: string
1684
- only?: ('index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy')[]
1685
- except?: ('index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy')[]
1686
- middleware?: (BuiltInMiddleware | MiddlewareWithParams<BuiltInMiddleware>)[]
1687
- bindings?: Record<string, string>
1688
- names?: Partial<Record<'index' | 'show' | 'create' | 'store' | 'edit' | 'update' | 'destroy', string>>
1689
- }
1690
-
1691
- /**
1692
- * Stream route handler with typed path parameters
1693
- */
1694
- export interface StreamRouteHandler<TPath extends string = string> {
1695
- (
1696
- req: EnhancedRequest & { params: ExtractRouteParams<TPath> },
1697
- writer: StreamWriter
1698
- ): Promise<void> | void
1699
- }
1700
-
1701
- /**
1702
- * SSE route handler with typed path parameters
1703
- */
1704
- export interface SSERouteHandler<TPath extends string = string> {
1705
- (
1706
- req: EnhancedRequest & { params: ExtractRouteParams<TPath> }
1707
- ): SSEGenerator | AsyncGenerator<SSEEvent, void, unknown>
1708
- }
1709
-
1710
- /**
1711
- * Route matching result
1712
- */
1713
- export interface MatchResult {
1714
- route: Route
1715
- params: Record<string, string>
1716
- }
1717
-
1718
- /**
1719
- * URL pattern match result
1720
- */
1721
- export interface PatternMatchResult {
1722
- pathname: {
1723
- groups: Record<string, string>
1724
- }
1725
- }
1726
-
1727
- /**
1728
- * Streaming response options
1729
- */
1730
- export interface StreamingOptions {
1731
- headers?: Record<string, string>
1732
- status?: number
1733
- }
1734
-
1735
- /**
1736
- * SSE (Server-Sent Events) data structure
1737
- */
1738
- export interface SSEData {
1739
- data: any
1740
- event?: string
1741
- id?: string
1742
- retry?: number
1743
- }
1744
-
1745
- /**
1746
- * Direct streaming writer interface
1747
- */
1748
- export interface DirectStreamWriter {
1749
- write: (chunk: string | Uint8Array) => void
1750
- close: () => void
1751
- }
1752
-
1753
- /**
1754
- * Buffered streaming writer interface
1755
- */
1756
- export interface BufferedStreamWriter {
1757
- write: (chunk: string | Uint8Array) => void
1758
- flush: () => void
1759
- end: () => void
1760
- }
1761
-
1762
- /**
1763
- * Buffered streaming options
1764
- */
1765
- export interface BufferedStreamOptions {
1766
- highWaterMark?: number
1767
- asUint8Array?: boolean
1768
- }
1769
-
1770
- /**
1771
- * Async generator function type for streaming
1772
- */
1773
- export type StreamGenerator<T = unknown> = () => AsyncGenerator<T, void, unknown>
1774
-
1775
- /**
1776
- * Direct stream handler function type
1777
- */
1778
- export type DirectStreamHandler = (_writer: DirectStreamWriter) => Promise<void>
1779
-
1780
- /**
1781
- * Buffered stream handler function type
1782
- */
1783
- export type BufferedStreamHandler = (_writer: BufferedStreamWriter) => Promise<void>
1784
-
1785
- /**
1786
- * Transform function type for stream transformation
1787
- */
1788
- export type TransformFunction<T = Uint8Array, R = string | Uint8Array> = (_chunk: T) => R | Promise<R>
1789
-
1790
- /**
1791
- * Advanced Error Handling Types
1792
- */
1793
- export interface ErrorContext {
1794
- requestId?: string
1795
- userId?: string | number
1796
- traceId?: string
1797
- spanId?: string
1798
- route?: string
1799
- method?: string
1800
- url?: string
1801
- userAgent?: string
1802
- ip?: string
1803
- timestamp?: Date
1804
- metadata?: ErrorMetadata
1805
- }
1806
-
1807
- export interface ErrorReportingConfig {
1808
- enabled: boolean
1809
- service: 'sentry' | 'bugsnag' | 'custom'
1810
- dsn?: string
1811
- apiKey?: string
1812
- environment?: string
1813
- release?: string
1814
- sampleRate?: number
1815
- beforeSend?: (error: Error, context: ErrorContext) => Error | null
1816
- filters?: {
1817
- ignoreErrors?: (string | RegExp)[]
1818
- ignoreCodes?: string[]
1819
- ignoreUrls?: (string | RegExp)[]
1820
- allowUrls?: (string | RegExp)[]
1821
- }
1822
- tags?: Record<string, string>
1823
- user?: {
1824
- id?: string
1825
- email?: string
1826
- username?: string
1827
- }
1828
- extra?: Record<string, unknown>
1829
- breadcrumbs?: {
1830
- enabled: boolean
1831
- maxBreadcrumbs: number
1832
- }
1833
- performance?: {
1834
- enabled: boolean
1835
- tracesSampleRate: number
1836
- }
1837
- }
1838
-
1839
- export interface CircuitBreakerConfig {
1840
- name: string
1841
- failureThreshold: number
1842
- recoveryTimeout: number
1843
- timeout: number
1844
- monitoringPeriod: number
1845
- minimumRequests: number
1846
- errorThresholdPercentage: number
1847
- halfOpenMaxCalls: number
1848
- resetTimeout: number
1849
- onStateChange?: (state: 'CLOSED' | 'OPEN' | 'HALF_OPEN', name: string) => void
1850
- onFailure?: (error: Error, name: string) => void
1851
- onSuccess?: (name: string) => void
1852
- shouldTripOnError?: (error: Error) => boolean
1853
- }
1854
-
1855
- export interface DegradationConfig {
1856
- enabled: boolean
1857
- fallbackStrategies: {
1858
- [serviceName: string]: {
1859
- type: 'cache' | 'static' | 'simplified' | 'redirect' | 'custom'
1860
- priority: number
1861
- timeout: number
1862
- retries: number
1863
- backoff: {
1864
- type: 'fixed' | 'exponential'
1865
- delay: number
1866
- maxDelay?: number
1867
- }
1868
- fallbackHandler?: (error: FallbackError, context: ErrorContext) => Promise<Response>
1869
- cacheConfig?: {
1870
- key: string
1871
- ttl: number
1872
- staleWhileRevalidate: boolean
1873
- }
1874
- staticResponse?: {
1875
- status: number
1876
- body: StaticResponseBody
1877
- headers?: Record<string, string>
1878
- }
1879
- redirectConfig?: {
1880
- url: string
1881
- permanent: boolean
1882
- }
1883
- }
1884
- }
1885
- healthChecks: {
1886
- [serviceName: string]: {
1887
- enabled: boolean
1888
- endpoint: string
1889
- interval: number
1890
- timeout: number
1891
- retries: number
1892
- expectedStatus: number[]
1893
- expectedBody?: string | RegExp
1894
- headers?: Record<string, string>
1895
- onHealthy?: () => void
1896
- onUnhealthy?: (error: Error) => void
1897
- }
1898
- }
1899
- monitoring: {
1900
- enabled: boolean
1901
- alertThresholds: {
1902
- errorRate: number
1903
- responseTime: number
1904
- availability: number
1905
- }
1906
- }
1907
- }
1908
-
1909
- /**
1910
- * Request/Response Enhancement Types
1911
- */
1912
- export interface RequestMacroMethods {
1913
- // Content type detection
1914
- wantsJson: () => boolean
1915
- wantsHtml: () => boolean
1916
- wantsXml: () => boolean
1917
- expectsJson: () => boolean
1918
-
1919
- // Request information
1920
- isAjax: () => boolean
1921
- isPjax: () => boolean
1922
- isMobile: () => boolean
1923
- isBot: () => boolean
1924
- isSecure: () => boolean
1925
-
1926
- // Client information
1927
- ip: () => string
1928
- ips: () => string[]
1929
- userAgent: () => string
1930
- referer: () => string | null
1931
-
1932
- // Authentication
1933
- bearerToken: () => string | null
1934
- basicAuth: () => { username: string, password: string } | null
1935
-
1936
- // Headers
1937
- hasHeader: (name: string) => boolean
1938
- header: (name: string, defaultValue?: string) => string | null
1939
- allHeaders: () => Record<string, string>
1940
-
1941
- // Input handling
1942
- input: <T = InputValue>(key: string, defaultValue?: T) => T
1943
- all: () => RequestInput
1944
- only: (keys: string[]) => RequestInput
1945
- except: (keys: string[]) => RequestInput
1946
-
1947
- // Validation checks
1948
- has: (key: string) => boolean
1949
- hasAny: (keys: string[]) => boolean
1950
- missing: (key: string) => boolean
1951
- filled: (key: string) => boolean
1952
-
1953
- // Query and params
1954
- getQuery: <T = InputValue>(key?: string, defaultValue?: T) => T
1955
- param: <T = InputValue>(key: string, defaultValue?: T) => T
1956
-
1957
- // Cookies
1958
- cookie: (name: string, defaultValue?: string) => string | null
1959
- cookies: () => Record<string, string>
1960
-
1961
- // Files
1962
- file: (name: string) => FileInfo | null
1963
- hasFile: (name: string) => boolean
1964
-
1965
- // URL utilities
1966
- path: () => string
1967
- fullUrl: () => string
1968
- root: () => string
1969
- is: (pattern: string) => boolean
1970
- route: () => string | null
1971
-
1972
- // Utilities
1973
- fingerprint: () => string
1974
- signature: (secret: string) => string
1975
- merge: (data: RequestInput) => void
1976
- replace: (data: RequestInput) => void
1977
- age: () => number
1978
- isFromTrustedProxy: (trustedProxies?: string[]) => boolean
1979
- contentLength: () => number
1980
- contentType: () => string | null
1981
- isContentType: (type: string) => boolean
1982
- }
1983
-
1984
- /**
1985
- * Enhanced streaming generator types with extreme narrowing
1986
- */
1987
- export type StreamGeneratorSync<T = string | Uint8Array> = () => Generator<T, void, unknown>
1988
- export type AsyncStreamGenerator<T = string | Uint8Array> = () => AsyncGenerator<T, void, unknown>
1989
- export type StreamCallbackGenerator<T = string | Uint8Array> = StreamGenerator<T> | AsyncStreamGenerator<T>
1990
-
1991
- /**
1992
- * SSE Event generator with strict typing
1993
- */
1994
- export type SSEEventGenerator<T = unknown> = () => Generator<SSEEvent<T>, void, unknown> | AsyncGenerator<SSEEvent<T>, void, unknown>
1995
-
1996
- /**
1997
- * Extreme narrow types for Laravel-style methods with template literal patterns
1998
- */
1999
- export interface EnhancedLaravelStreamingMethods {
2000
- /**
2001
- * Laravel-style response()->stream() with extreme type narrowing
2002
- */
2003
- stream: <T extends string | Uint8Array = string>(
2004
- callback: StreamCallbackGenerator<T>,
2005
- status?: ResponseStatus,
2006
- headers?: Record<string, string>
2007
- ) => Response
2008
-
2009
- /**
2010
- * Laravel-style response()->streamJson() with strict object key typing
2011
- */
2012
- streamJson: <T, K extends string = string>(
2013
- data: Record<K, Iterable<T> | AsyncIterable<T>>,
2014
- status?: ResponseStatus,
2015
- headers?: Record<string, string>
2016
- ) => Response
2017
-
2018
- /**
2019
- * Laravel-style response()->eventStream() with strict SSE typing
2020
- */
2021
- eventStream: <T = unknown>(
2022
- callback: SSEEventGenerator<T>,
2023
- headers?: Record<string, string>
2024
- ) => Response
2025
-
2026
- /**
2027
- * Laravel-style response()->streamDownload() with filename validation
2028
- */
2029
- streamDownload: <T extends string | Uint8Array = string>(
2030
- callback: StreamCallbackGenerator<T>,
2031
- filename: `${string}.${string}`, // Must have extension
2032
- headers?: Record<string, string>
2033
- ) => Response
2034
- }
2035
-
2036
- /**
2037
- * Enhanced model binding with strict key typing
2038
- */
2039
- export interface EnhancedLaravelModelBindingMethods {
2040
- /**
2041
- * Laravel-style Route::model() with key validation
2042
- */
2043
- model: <T, K extends string>(
2044
- key: K,
2045
- modelClass: string | ((_value: string) => Promise<T | null>),
2046
- callback?: (model: T | null) => Response | null
2047
- ) => Router & { [P in K]: T }
2048
-
2049
- /**
2050
- * Scoped bindings with relationship validation
2051
- */
2052
- scopedBindings: <Parent extends string, Child extends string>(
2053
- bindings: Record<Child, Parent>
2054
- ) => MiddlewareHandler
2055
- }