@stacksjs/bun-router 0.0.5 → 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 (269) hide show
  1. package/dist/auth.d.ts +134 -0
  2. package/dist/cache/lru-cache.d.ts +139 -0
  3. package/dist/cache/middleware-memoization.d.ts +151 -0
  4. package/dist/cache/route-cache-warmer.d.ts +161 -0
  5. package/dist/cache/sqlite-cache.d.ts +209 -0
  6. package/dist/cache/streaming-cache.d.ts +132 -0
  7. package/dist/cli/colors.d.ts +15 -0
  8. package/dist/cli/index.d.ts +10 -0
  9. package/dist/cli/middleware.d.ts +31 -0
  10. package/dist/cli/openapi.d.ts +17 -0
  11. package/dist/cli/router.d.ts +15 -0
  12. package/dist/cli/routes.d.ts +29 -0
  13. package/dist/cli/utils.d.ts +74 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +1 -1
  16. package/dist/config.d.ts +7 -0
  17. package/dist/container/container.d.ts +273 -0
  18. package/dist/container/contextual-binding.d.ts +240 -0
  19. package/dist/container/decorators.d.ts +141 -0
  20. package/dist/container/service-provider.d.ts +285 -0
  21. package/dist/development/hot-reload.d.ts +187 -0
  22. package/dist/development/index.d.ts +167 -0
  23. package/dist/development/performance-profiler.d.ts +217 -0
  24. package/dist/development/route-debugger.d.ts +154 -0
  25. package/dist/development/route-inspector.d.ts +211 -0
  26. package/dist/development/typescript-utilities.d.ts +209 -0
  27. package/dist/docs.d.ts +11 -0
  28. package/dist/errors/circuit-breaker.d.ts +195 -0
  29. package/dist/errors/error-handler.d.ts +88 -0
  30. package/dist/errors/error-reporting.d.ts +144 -0
  31. package/dist/errors/exceptions.d.ts +184 -0
  32. package/dist/errors/graceful-degradation.d.ts +154 -0
  33. package/dist/errors/index.d.ts +9 -0
  34. package/dist/errors/router-errors.d.ts +110 -0
  35. package/dist/file-serving/static-files.d.ts +143 -0
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.js +319 -205
  38. package/dist/middleware/auth.d.ts +63 -0
  39. package/dist/middleware/content_security_policy.d.ts +53 -0
  40. package/dist/middleware/cors.d.ts +5 -0
  41. package/dist/middleware/csrf.d.ts +7 -0
  42. package/dist/middleware/ddos_protection.d.ts +39 -0
  43. package/dist/middleware/file_security.d.ts +26 -0
  44. package/dist/middleware/file_upload.d.ts +38 -0
  45. package/dist/middleware/helmet.d.ts +54 -0
  46. package/dist/middleware/index.d.ts +44 -0
  47. package/dist/middleware/input_validation.d.ts +45 -0
  48. package/dist/middleware/json_body.d.ts +4 -0
  49. package/dist/middleware/performance_alerting.d.ts +87 -0
  50. package/dist/middleware/performance_dashboard.d.ts +87 -0
  51. package/dist/middleware/performance_monitor.d.ts +209 -0
  52. package/dist/middleware/pipeline.d.ts +131 -0
  53. package/dist/middleware/rate_limit.d.ts +36 -0
  54. package/dist/middleware/request_id.d.ts +4 -0
  55. package/dist/middleware/request_signing.d.ts +153 -0
  56. package/dist/middleware/request_tracer.d.ts +72 -0
  57. package/dist/middleware/response_cache.d.ts +97 -0
  58. package/dist/middleware/security.d.ts +69 -0
  59. package/dist/middleware/security_suite.d.ts +46 -0
  60. package/dist/middleware/session.d.ts +23 -0
  61. package/dist/model-binding/index.d.ts +2 -0
  62. package/dist/model-binding/model-middleware.d.ts +118 -0
  63. package/dist/model-binding/model-registry.d.ts +164 -0
  64. package/dist/model-binding.d.ts +185 -0
  65. package/dist/model-resolver-factory.d.ts +31 -0
  66. package/dist/observability/correlation.d.ts +187 -0
  67. package/dist/observability/health-checks.d.ts +186 -0
  68. package/dist/observability/index.d.ts +60 -0
  69. package/dist/observability/integration.d.ts +147 -0
  70. package/dist/observability/metrics.d.ts +184 -0
  71. package/dist/observability/tracing.d.ts +187 -0
  72. package/dist/optimization/bun-utilities.d.ts +224 -0
  73. package/dist/query-builder-integration.d.ts +36 -0
  74. package/dist/request/context.d.ts +34 -0
  75. package/dist/request/enhanced-request.d.ts +213 -0
  76. package/dist/request/macros.d.ts +300 -0
  77. package/dist/response/macros.d.ts +245 -0
  78. package/dist/response/response-factory.d.ts +133 -0
  79. package/dist/router/api-routes.d.ts +5 -0
  80. package/dist/router/file-based-routing.d.ts +118 -0
  81. package/dist/router/file-streaming.d.ts +5 -0
  82. package/dist/router/fluent-router.d.ts +315 -0
  83. package/dist/router/fluent-routing.d.ts +271 -0
  84. package/dist/router/group-organization.d.ts +5 -0
  85. package/dist/router/handler-resolver.d.ts +24 -0
  86. package/dist/router/http-methods.d.ts +10 -0
  87. package/dist/router/index.d.ts +113 -0
  88. package/dist/router/middleware-groups.d.ts +94 -0
  89. package/dist/router/middleware-integration.d.ts +112 -0
  90. package/dist/router/middleware.d.ts +5 -0
  91. package/dist/router/model-binding.d.ts +5 -0
  92. package/dist/router/optimized-route-matching.d.ts +6 -0
  93. package/dist/router/route-building.d.ts +5 -0
  94. package/dist/router/route-compiler.d.ts +153 -0
  95. package/dist/router/route-matching.d.ts +5 -0
  96. package/dist/router/route-trie.d.ts +114 -0
  97. package/dist/router/router.d.ts +276 -0
  98. package/dist/router/server.d.ts +5 -0
  99. package/dist/router/validation-integration.d.ts +170 -0
  100. package/dist/router/view-rendering.d.ts +5 -0
  101. package/dist/router/websocket.d.ts +5 -0
  102. package/dist/routing/route-caching.d.ts +129 -0
  103. package/dist/routing/route-throttling.d.ts +150 -0
  104. package/dist/routing/subdomain-routing.d.ts +206 -0
  105. package/dist/session/database-store.d.ts +51 -0
  106. package/dist/session/file-store.d.ts +22 -0
  107. package/dist/session/index.d.ts +106 -0
  108. package/dist/session/memory-store.d.ts +21 -0
  109. package/dist/session/redis-store.d.ts +31 -0
  110. package/dist/streaming/index.d.ts +3 -0
  111. package/dist/streaming/sse-handler.d.ts +138 -0
  112. package/dist/streaming/stream-handler.d.ts +114 -0
  113. package/dist/testing/auth-testing.d.ts +156 -0
  114. package/dist/testing/file-upload-testing.d.ts +190 -0
  115. package/dist/testing/index.d.ts +10 -0
  116. package/dist/testing/middleware-testing.d.ts +138 -0
  117. package/dist/testing/model-binding-testing.d.ts +186 -0
  118. package/dist/testing/performance-testing.d.ts +235 -0
  119. package/dist/testing/test-client.d.ts +117 -0
  120. package/dist/testing/test-request.d.ts +85 -0
  121. package/dist/testing/test-response.d.ts +90 -0
  122. package/dist/testing/types.d.ts +207 -0
  123. package/dist/testing/websocket-testing.d.ts +227 -0
  124. package/dist/types/controller-types.d.ts +208 -0
  125. package/dist/types/core.d.ts +543 -0
  126. package/dist/types/middleware-types.d.ts +227 -0
  127. package/dist/types/request-response-augmentation.d.ts +261 -0
  128. package/dist/types/route-inference.d.ts +168 -0
  129. package/dist/types.d.ts +1776 -0
  130. package/dist/url.d.ts +56 -0
  131. package/dist/utils/index.d.ts +1 -0
  132. package/dist/utils/query-preservation.d.ts +48 -0
  133. package/dist/utils.d.ts +69 -0
  134. package/dist/validation/validator.d.ts +140 -0
  135. package/dist/websocket/clustering.d.ts +185 -0
  136. package/package.json +3 -2
  137. package/src/auth.ts +469 -0
  138. package/src/cache/lru-cache.ts +457 -0
  139. package/src/cache/middleware-memoization.ts +531 -0
  140. package/src/cache/route-cache-warmer.ts +486 -0
  141. package/src/cache/sqlite-cache.ts +783 -0
  142. package/src/cache/streaming-cache.ts +572 -0
  143. package/src/cli/colors.ts +29 -0
  144. package/src/cli/index.ts +287 -0
  145. package/src/cli/middleware.ts +291 -0
  146. package/src/cli/openapi.ts +407 -0
  147. package/src/cli/router.ts +188 -0
  148. package/src/cli/routes.ts +265 -0
  149. package/src/cli/utils.ts +531 -0
  150. package/src/cli.ts +5 -0
  151. package/src/config.ts +322 -0
  152. package/src/container/container.ts +740 -0
  153. package/src/container/contextual-binding.ts +603 -0
  154. package/src/container/decorators.ts +359 -0
  155. package/src/container/service-provider.ts +596 -0
  156. package/src/development/hot-reload.ts +673 -0
  157. package/src/development/index.ts +499 -0
  158. package/src/development/performance-profiler.ts +717 -0
  159. package/src/development/route-debugger.ts +527 -0
  160. package/src/development/route-inspector.ts +749 -0
  161. package/src/development/typescript-utilities.ts +678 -0
  162. package/src/docs.ts +397 -0
  163. package/src/errors/circuit-breaker.ts +732 -0
  164. package/src/errors/error-handler.ts +569 -0
  165. package/src/errors/error-reporting.ts +672 -0
  166. package/src/errors/exceptions.ts +536 -0
  167. package/src/errors/graceful-degradation.ts +621 -0
  168. package/src/errors/index.ts +21 -0
  169. package/src/errors/router-errors.ts +632 -0
  170. package/src/file-serving/static-files.ts +581 -0
  171. package/src/index.ts +14 -0
  172. package/src/middleware/auth.ts +219 -0
  173. package/src/middleware/content_security_policy.ts +215 -0
  174. package/src/middleware/cors.ts +74 -0
  175. package/src/middleware/csrf.ts +108 -0
  176. package/src/middleware/ddos_protection.ts +255 -0
  177. package/src/middleware/file_security.ts +191 -0
  178. package/src/middleware/file_upload.ts +264 -0
  179. package/src/middleware/helmet.ts +268 -0
  180. package/src/middleware/index.ts +117 -0
  181. package/src/middleware/input_validation.ts +449 -0
  182. package/src/middleware/json_body.ts +37 -0
  183. package/src/middleware/performance_alerting.ts +538 -0
  184. package/src/middleware/performance_dashboard.ts +661 -0
  185. package/src/middleware/performance_monitor.ts +943 -0
  186. package/src/middleware/pipeline.ts +489 -0
  187. package/src/middleware/rate_limit.ts +245 -0
  188. package/src/middleware/request_id.ts +36 -0
  189. package/src/middleware/request_signing.ts +636 -0
  190. package/src/middleware/request_tracer.ts +636 -0
  191. package/src/middleware/response_cache.ts +743 -0
  192. package/src/middleware/security.ts +482 -0
  193. package/src/middleware/security_suite.ts +257 -0
  194. package/src/middleware/session.ts +91 -0
  195. package/src/model-binding/index.ts +18 -0
  196. package/src/model-binding/model-middleware.ts +425 -0
  197. package/src/model-binding/model-registry.ts +550 -0
  198. package/src/model-binding.ts +370 -0
  199. package/src/model-resolver-factory.ts +106 -0
  200. package/src/observability/correlation.ts +691 -0
  201. package/src/observability/health-checks.ts +729 -0
  202. package/src/observability/index.ts +184 -0
  203. package/src/observability/integration.ts +548 -0
  204. package/src/observability/metrics.ts +753 -0
  205. package/src/observability/tracing.ts +638 -0
  206. package/src/optimization/bun-utilities.ts +778 -0
  207. package/src/query-builder-integration.ts +137 -0
  208. package/src/request/context.ts +62 -0
  209. package/src/request/enhanced-request.ts +857 -0
  210. package/src/request/macros.ts +688 -0
  211. package/src/response/macros.ts +612 -0
  212. package/src/response/response-factory.ts +588 -0
  213. package/src/router/api-routes.ts +243 -0
  214. package/src/router/file-based-routing.ts +670 -0
  215. package/src/router/file-streaming.ts +372 -0
  216. package/src/router/fluent-router.ts +927 -0
  217. package/src/router/fluent-routing.ts +797 -0
  218. package/src/router/group-organization.ts +213 -0
  219. package/src/router/handler-resolver.ts +291 -0
  220. package/src/router/http-methods.ts +377 -0
  221. package/src/router/index.ts +185 -0
  222. package/src/router/middleware-groups.ts +222 -0
  223. package/src/router/middleware-integration.ts +399 -0
  224. package/src/router/middleware.ts +231 -0
  225. package/src/router/model-binding.ts +215 -0
  226. package/src/router/optimized-route-matching.ts +253 -0
  227. package/src/router/route-building.ts +212 -0
  228. package/src/router/route-compiler.ts +702 -0
  229. package/src/router/route-matching.ts +349 -0
  230. package/src/router/route-trie.ts +464 -0
  231. package/src/router/router.ts +1508 -0
  232. package/src/router/server.ts +406 -0
  233. package/src/router/validation-integration.ts +443 -0
  234. package/src/router/view-rendering.ts +233 -0
  235. package/src/router/websocket.ts +100 -0
  236. package/src/routing/route-caching.ts +402 -0
  237. package/src/routing/route-throttling.ts +469 -0
  238. package/src/routing/subdomain-routing.ts +492 -0
  239. package/src/session/database-store.ts +109 -0
  240. package/src/session/file-store.ts +148 -0
  241. package/src/session/index.ts +244 -0
  242. package/src/session/memory-store.ts +88 -0
  243. package/src/session/redis-store.ts +93 -0
  244. package/src/streaming/index.ts +17 -0
  245. package/src/streaming/sse-handler.ts +482 -0
  246. package/src/streaming/stream-handler.ts +552 -0
  247. package/src/testing/auth-testing.ts +446 -0
  248. package/src/testing/file-upload-testing.ts +543 -0
  249. package/src/testing/index.ts +10 -0
  250. package/src/testing/middleware-testing.ts +322 -0
  251. package/src/testing/model-binding-testing.ts +645 -0
  252. package/src/testing/performance-testing.ts +738 -0
  253. package/src/testing/test-client.ts +310 -0
  254. package/src/testing/test-request.ts +315 -0
  255. package/src/testing/test-response.ts +332 -0
  256. package/src/testing/types.ts +224 -0
  257. package/src/testing/websocket-testing.ts +590 -0
  258. package/src/types/controller-types.ts +385 -0
  259. package/src/types/core.ts +683 -0
  260. package/src/types/middleware-types.ts +419 -0
  261. package/src/types/request-response-augmentation.ts +489 -0
  262. package/src/types/route-inference.ts +357 -0
  263. package/src/types.ts +2049 -0
  264. package/src/url.ts +126 -0
  265. package/src/utils/index.ts +1 -0
  266. package/src/utils/query-preservation.ts +201 -0
  267. package/src/utils.ts +327 -0
  268. package/src/validation/validator.ts +685 -0
  269. package/src/websocket/clustering.ts +762 -0
@@ -0,0 +1,685 @@
1
+ /**
2
+ * Request/Response Enhancements - Validation System
3
+ *
4
+ * Laravel-style validation with custom rules and error handling
5
+ */
6
+
7
+ import type { EnhancedRequest, NextFunction } from '../types'
8
+ import { ValidationException } from '../errors/exceptions'
9
+
10
+ export interface ValidationRule {
11
+ name: string
12
+ validate: (value: any, parameters: string[], field: string, data: Record<string, any>) => Promise<boolean> | boolean
13
+ message: string | ((_field: string, _parameters: string[]) => string)
14
+ }
15
+
16
+ export interface ValidationRules {
17
+ [field: string]: string | ValidationRule[]
18
+ }
19
+
20
+ export interface ValidationErrors {
21
+ [field: string]: string[]
22
+ }
23
+
24
+ export interface ValidatorConfig {
25
+ stopOnFirstFailure?: boolean
26
+ customMessages?: Record<string, string>
27
+ customAttributes?: Record<string, string>
28
+ bail?: boolean
29
+ }
30
+
31
+ /**
32
+ * Built-in validation rules
33
+ */
34
+ export const BuiltInRules: Record<string, ValidationRule> = {
35
+ required: {
36
+ name: 'required',
37
+ validate: (value) => {
38
+ if (value === null || value === undefined)
39
+ return false
40
+ if (typeof value === 'string')
41
+ return value.trim().length > 0
42
+ if (Array.isArray(value))
43
+ return value.length > 0
44
+ if (typeof value === 'object')
45
+ return Object.keys(value).length > 0
46
+ return true
47
+ },
48
+ message: 'The :field field is required.',
49
+ },
50
+
51
+ string: {
52
+ name: 'string',
53
+ validate: value => typeof value === 'string',
54
+ message: 'The :field field must be a string.',
55
+ },
56
+
57
+ number: {
58
+ name: 'number',
59
+ validate: value => typeof value === 'number' && !Number.isNaN(value),
60
+ message: 'The :field field must be a number.',
61
+ },
62
+
63
+ integer: {
64
+ name: 'integer',
65
+ validate: value => Number.isInteger(Number(value)),
66
+ message: 'The :field field must be an integer.',
67
+ },
68
+
69
+ boolean: {
70
+ name: 'boolean',
71
+ validate: value => typeof value === 'boolean' || value === 'true' || value === 'false' || value === '1' || value === '0',
72
+ message: 'The :field field must be true or false.',
73
+ },
74
+
75
+ email: {
76
+ name: 'email',
77
+ validate: (value) => {
78
+ const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
79
+ return typeof value === 'string' && emailRegex.test(value)
80
+ },
81
+ message: 'The :field field must be a valid email address.',
82
+ },
83
+
84
+ url: {
85
+ name: 'url',
86
+ validate: (value) => {
87
+ try {
88
+ const url = new URL(value)
89
+ return Boolean(url)
90
+ }
91
+ catch {
92
+ return false
93
+ }
94
+ },
95
+ message: 'The :field field must be a valid URL.',
96
+ },
97
+
98
+ min: {
99
+ name: 'min',
100
+ validate: (value, parameters) => {
101
+ const min = Number(parameters[0])
102
+ if (typeof value === 'string')
103
+ return value.length >= min
104
+ if (typeof value === 'number')
105
+ return value >= min
106
+ if (Array.isArray(value))
107
+ return value.length >= min
108
+ return false
109
+ },
110
+ message: (field, parameters) => `The ${field} field must be at least ${parameters[0]} characters.`,
111
+ },
112
+
113
+ max: {
114
+ name: 'max',
115
+ validate: (value, parameters) => {
116
+ const max = Number(parameters[0])
117
+ if (typeof value === 'string')
118
+ return value.length <= max
119
+ if (typeof value === 'number')
120
+ return value <= max
121
+ if (Array.isArray(value))
122
+ return value.length <= max
123
+ return false
124
+ },
125
+ message: (field, parameters) => `The ${field} field must not exceed ${parameters[0]} characters.`,
126
+ },
127
+
128
+ between: {
129
+ name: 'between',
130
+ validate: (value, parameters) => {
131
+ const min = Number(parameters[0])
132
+ const max = Number(parameters[1])
133
+ if (typeof value === 'string')
134
+ return value.length >= min && value.length <= max
135
+ if (typeof value === 'number')
136
+ return value >= min && value <= max
137
+ if (Array.isArray(value))
138
+ return value.length >= min && value.length <= max
139
+ return false
140
+ },
141
+ message: (field, parameters) => `The ${field} field must be between ${parameters[0]} and ${parameters[1]}.`,
142
+ },
143
+
144
+ in: {
145
+ name: 'in',
146
+ validate: (value, parameters) => parameters.includes(String(value)),
147
+ message: (field, parameters) => `The ${field} field must be one of: ${parameters.join(', ')}.`,
148
+ },
149
+
150
+ notIn: {
151
+ name: 'not_in',
152
+ validate: (value, parameters) => !parameters.includes(String(value)),
153
+ message: (field, parameters) => `The ${field} field must not be one of: ${parameters.join(', ')}.`,
154
+ },
155
+
156
+ regex: {
157
+ name: 'regex',
158
+ validate: (value, parameters) => {
159
+ const pattern = new RegExp(parameters[0])
160
+ return typeof value === 'string' && pattern.test(value)
161
+ },
162
+ message: 'The :field field format is invalid.',
163
+ },
164
+
165
+ alpha: {
166
+ name: 'alpha',
167
+ validate: value => typeof value === 'string' && /^[a-z]+$/i.test(value),
168
+ message: 'The :field field must contain only letters.',
169
+ },
170
+
171
+ alphaNum: {
172
+ name: 'alpha_num',
173
+ validate: value => typeof value === 'string' && /^[a-z0-9]+$/i.test(value),
174
+ message: 'The :field field must contain only letters and numbers.',
175
+ },
176
+
177
+ alphaDash: {
178
+ name: 'alpha_dash',
179
+ validate: value => typeof value === 'string' && /^[\w-]+$/.test(value),
180
+ message: 'The :field field must contain only letters, numbers, dashes, and underscores.',
181
+ },
182
+
183
+ date: {
184
+ name: 'date',
185
+ validate: (value) => {
186
+ const date = new Date(value)
187
+ return !Number.isNaN(date.getTime())
188
+ },
189
+ message: 'The :field field must be a valid date.',
190
+ },
191
+
192
+ dateAfter: {
193
+ name: 'after',
194
+ validate: (value, parameters) => {
195
+ const date = new Date(value)
196
+ const afterDate = new Date(parameters[0])
197
+ return !Number.isNaN(date.getTime()) && !Number.isNaN(afterDate.getTime()) && date > afterDate
198
+ },
199
+ message: (field, parameters) => `The ${field} field must be after ${parameters[0]}.`,
200
+ },
201
+
202
+ dateBefore: {
203
+ name: 'before',
204
+ validate: (value, parameters) => {
205
+ const date = new Date(value)
206
+ const beforeDate = new Date(parameters[0])
207
+ return !Number.isNaN(date.getTime()) && !Number.isNaN(beforeDate.getTime()) && date < beforeDate
208
+ },
209
+ message: (field, parameters) => `The ${field} field must be before ${parameters[0]}.`,
210
+ },
211
+
212
+ confirmed: {
213
+ name: 'confirmed',
214
+ validate: (value, parameters, field, data) => {
215
+ const confirmationField = parameters[0] || `${field}_confirmation`
216
+ return value === data[confirmationField]
217
+ },
218
+ message: 'The :field confirmation does not match.',
219
+ },
220
+
221
+ same: {
222
+ name: 'same',
223
+ validate: (value, parameters, field, data) => {
224
+ return value === data[parameters[0]]
225
+ },
226
+ message: (field, parameters) => `The ${field} field must match ${parameters[0]}.`,
227
+ },
228
+
229
+ different: {
230
+ name: 'different',
231
+ validate: (value, parameters, field, data) => {
232
+ return value !== data[parameters[0]]
233
+ },
234
+ message: (field, parameters) => `The ${field} field must be different from ${parameters[0]}.`,
235
+ },
236
+
237
+ json: {
238
+ name: 'json',
239
+ validate: (value) => {
240
+ try {
241
+ JSON.parse(value)
242
+ return true
243
+ }
244
+ catch {
245
+ return false
246
+ }
247
+ },
248
+ message: 'The :field field must be valid JSON.',
249
+ },
250
+
251
+ uuid: {
252
+ name: 'uuid',
253
+ validate: (value) => {
254
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
255
+ return typeof value === 'string' && uuidRegex.test(value)
256
+ },
257
+ message: 'The :field field must be a valid UUID.',
258
+ },
259
+
260
+ array: {
261
+ name: 'array',
262
+ validate: value => Array.isArray(value),
263
+ message: 'The :field field must be an array.',
264
+ },
265
+
266
+ object: {
267
+ name: 'object',
268
+ validate: value => typeof value === 'object' && value !== null && !Array.isArray(value),
269
+ message: 'The :field field must be an object.',
270
+ },
271
+ }
272
+
273
+ /**
274
+ * Database validation rules (require external implementation)
275
+ */
276
+ export const DatabaseRules: Record<string, ValidationRule> = {
277
+ unique: {
278
+ name: 'unique',
279
+ validate: async (_value, _parameters) => {
280
+ // This would need to be implemented with actual database queries
281
+ // For now, return true as a placeholder
282
+ console.warn('Database validation rule "unique" requires external implementation')
283
+ return true
284
+ },
285
+ message: 'The :field field must be unique.',
286
+ },
287
+
288
+ exists: {
289
+ name: 'exists',
290
+ validate: async (_value, _parameters) => {
291
+ // This would need to be implemented with actual database queries
292
+ // For now, return true as a placeholder
293
+ console.warn('Database validation rule "exists" requires external implementation')
294
+ return true
295
+ },
296
+ message: 'The selected :field is invalid.',
297
+ },
298
+ }
299
+
300
+ /**
301
+ * Main validator class
302
+ */
303
+ export class Validator {
304
+ private rules: Record<string, ValidationRule> = {}
305
+ private config: ValidatorConfig
306
+
307
+ constructor(config: ValidatorConfig = {}) {
308
+ this.config = {
309
+ stopOnFirstFailure: false,
310
+ bail: false,
311
+ ...config,
312
+ }
313
+
314
+ // Register built-in rules
315
+ this.registerRules(BuiltInRules)
316
+ }
317
+
318
+ /**
319
+ * Register validation rules
320
+ */
321
+ registerRule(rule: ValidationRule): void {
322
+ this.rules[rule.name] = rule
323
+ }
324
+
325
+ /**
326
+ * Register multiple validation rules
327
+ */
328
+ registerRules(rules: Record<string, ValidationRule>): void {
329
+ Object.values(rules).forEach(rule => this.registerRule(rule))
330
+ }
331
+
332
+ /**
333
+ * Parse validation rule string
334
+ */
335
+ private parseRuleString(ruleString: string): Array<{ name: string, parameters: string[] }> {
336
+ return ruleString.split('|').map((rule) => {
337
+ const [name, ...paramParts] = rule.split(':')
338
+ const parameters = paramParts.length > 0 ? paramParts.join(':').split(',') : []
339
+ return { name: name.trim(), parameters }
340
+ })
341
+ }
342
+
343
+ /**
344
+ * Validate data against rules
345
+ */
346
+ async validate(data: Record<string, any>, rules: ValidationRules): Promise<ValidationErrors> {
347
+ const errors: ValidationErrors = {}
348
+
349
+ for (const [field, fieldRules] of Object.entries(rules)) {
350
+ const fieldErrors: string[] = []
351
+ const value = this.getNestedValue(data, field)
352
+
353
+ // Parse rules if they're in string format
354
+ const parsedRules = typeof fieldRules === 'string'
355
+ ? this.parseRuleString(fieldRules)
356
+ : fieldRules.map(rule => ({ name: rule.name, parameters: [] }))
357
+
358
+ for (const { name, parameters } of parsedRules) {
359
+ const rule = this.rules[name]
360
+ if (!rule) {
361
+ console.warn(`Validation rule "${name}" not found`)
362
+ continue
363
+ }
364
+
365
+ try {
366
+ const isValid = await rule.validate(value, parameters, field, data)
367
+
368
+ if (!isValid) {
369
+ const message = this.formatErrorMessage(rule, field, parameters)
370
+ fieldErrors.push(message)
371
+
372
+ if (this.config.stopOnFirstFailure || this.config.bail) {
373
+ break
374
+ }
375
+ }
376
+ }
377
+ catch (error) {
378
+ console.error(`Error validating rule "${name}" for field "${field}":`, error)
379
+ fieldErrors.push(`Validation error for ${field}`)
380
+ }
381
+ }
382
+
383
+ if (fieldErrors.length > 0) {
384
+ errors[field] = fieldErrors
385
+ }
386
+ }
387
+
388
+ return errors
389
+ }
390
+
391
+ /**
392
+ * Validate and throw exception if validation fails
393
+ */
394
+ async validateOrFail(data: Record<string, any>, rules: ValidationRules): Promise<void> {
395
+ const errors = await this.validate(data, rules)
396
+
397
+ if (Object.keys(errors).length > 0) {
398
+ throw new ValidationException('Validation failed', errors)
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Get nested value from object using dot notation
404
+ */
405
+ private getNestedValue(obj: Record<string, any>, path: string): any {
406
+ return path.split('.').reduce((current, key) => {
407
+ return current && current[key] !== undefined ? current[key] : undefined
408
+ }, obj)
409
+ }
410
+
411
+ /**
412
+ * Format error message
413
+ */
414
+ private formatErrorMessage(rule: ValidationRule, field: string, parameters: string[]): string {
415
+ const customMessage = this.config.customMessages?.[`${field}.${rule.name}`]
416
+ || this.config.customMessages?.[rule.name]
417
+
418
+ if (customMessage) {
419
+ return this.replacePlaceholders(customMessage, field, parameters)
420
+ }
421
+
422
+ const message = typeof rule.message === 'function'
423
+ ? rule.message(field, parameters)
424
+ : rule.message
425
+
426
+ return this.replacePlaceholders(message, field, parameters)
427
+ }
428
+
429
+ /**
430
+ * Replace placeholders in error messages
431
+ */
432
+ private replacePlaceholders(message: string, field: string, parameters: string[]): string {
433
+ const fieldName = this.config.customAttributes?.[field] || field.replace(/_/g, ' ')
434
+
435
+ return message
436
+ .replace(/:field/g, fieldName)
437
+ .replace(/:attribute/g, fieldName)
438
+ .replace(/:value/g, parameters[0] || '')
439
+ .replace(/:other/g, parameters[1] || '')
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Global validator instance
445
+ */
446
+ export const globalValidator: Validator = new Validator()
447
+
448
+ /**
449
+ * Validation middleware factory
450
+ */
451
+ export function createValidationMiddleware(rules: ValidationRules, config?: ValidatorConfig) {
452
+ const validator = new Validator(config)
453
+
454
+ return async (req: EnhancedRequest, next: NextFunction): Promise<Response | null> => {
455
+ try {
456
+ // Get data from request body, query, and params
457
+ const data = {
458
+ ...req.query,
459
+ ...req.params,
460
+ ...(req.jsonBody || {}),
461
+ ...(req.formBody || {}),
462
+ }
463
+
464
+ await validator.validateOrFail(data, rules)
465
+
466
+ // Add validated data to request
467
+ req.validated = data
468
+
469
+ return await next()
470
+ }
471
+ catch (error) {
472
+ if (error instanceof ValidationException) {
473
+ throw error
474
+ }
475
+ throw new ValidationException('Validation error occurred')
476
+ }
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Validation rule builder for fluent API
482
+ */
483
+ export class ValidationRuleBuilder {
484
+ private rules: string[] = []
485
+
486
+ required(): this {
487
+ this.rules.push('required')
488
+ return this
489
+ }
490
+
491
+ string(): this {
492
+ this.rules.push('string')
493
+ return this
494
+ }
495
+
496
+ number(): this {
497
+ this.rules.push('number')
498
+ return this
499
+ }
500
+
501
+ integer(): this {
502
+ this.rules.push('integer')
503
+ return this
504
+ }
505
+
506
+ boolean(): this {
507
+ this.rules.push('boolean')
508
+ return this
509
+ }
510
+
511
+ email(): this {
512
+ this.rules.push('email')
513
+ return this
514
+ }
515
+
516
+ url(): this {
517
+ this.rules.push('url')
518
+ return this
519
+ }
520
+
521
+ min(value: number): this {
522
+ this.rules.push(`min:${value}`)
523
+ return this
524
+ }
525
+
526
+ max(value: number): this {
527
+ this.rules.push(`max:${value}`)
528
+ return this
529
+ }
530
+
531
+ between(min: number, max: number): this {
532
+ this.rules.push(`between:${min},${max}`)
533
+ return this
534
+ }
535
+
536
+ in(...values: string[]): this {
537
+ this.rules.push(`in:${values.join(',')}`)
538
+ return this
539
+ }
540
+
541
+ notIn(...values: string[]): this {
542
+ this.rules.push(`not_in:${values.join(',')}`)
543
+ return this
544
+ }
545
+
546
+ regex(pattern: string): this {
547
+ this.rules.push(`regex:${pattern}`)
548
+ return this
549
+ }
550
+
551
+ alpha(): this {
552
+ this.rules.push('alpha')
553
+ return this
554
+ }
555
+
556
+ alphaNum(): this {
557
+ this.rules.push('alpha_num')
558
+ return this
559
+ }
560
+
561
+ alphaDash(): this {
562
+ this.rules.push('alpha_dash')
563
+ return this
564
+ }
565
+
566
+ date(): this {
567
+ this.rules.push('date')
568
+ return this
569
+ }
570
+
571
+ after(date: string): this {
572
+ this.rules.push(`after:${date}`)
573
+ return this
574
+ }
575
+
576
+ before(date: string): this {
577
+ this.rules.push(`before:${date}`)
578
+ return this
579
+ }
580
+
581
+ confirmed(field?: string): this {
582
+ this.rules.push(field ? `confirmed:${field}` : 'confirmed')
583
+ return this
584
+ }
585
+
586
+ same(field: string): this {
587
+ this.rules.push(`same:${field}`)
588
+ return this
589
+ }
590
+
591
+ different(field: string): this {
592
+ this.rules.push(`different:${field}`)
593
+ return this
594
+ }
595
+
596
+ json(): this {
597
+ this.rules.push('json')
598
+ return this
599
+ }
600
+
601
+ uuid(): this {
602
+ this.rules.push('uuid')
603
+ return this
604
+ }
605
+
606
+ array(): this {
607
+ this.rules.push('array')
608
+ return this
609
+ }
610
+
611
+ object(): this {
612
+ this.rules.push('object')
613
+ return this
614
+ }
615
+
616
+ unique(table: string, column?: string): this {
617
+ this.rules.push(column ? `unique:${table},${column}` : `unique:${table}`)
618
+ return this
619
+ }
620
+
621
+ exists(table: string, column?: string): this {
622
+ this.rules.push(column ? `exists:${table},${column}` : `exists:${table}`)
623
+ return this
624
+ }
625
+
626
+ custom(ruleName: string, ...parameters: string[]): this {
627
+ this.rules.push(parameters.length > 0 ? `${ruleName}:${parameters.join(',')}` : ruleName)
628
+ return this
629
+ }
630
+
631
+ build(): string {
632
+ return this.rules.join('|')
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Factory function to create validation rule builder
638
+ */
639
+ export function rule(): ValidationRuleBuilder {
640
+ return new ValidationRuleBuilder()
641
+ }
642
+
643
+ /**
644
+ * Validation helper functions
645
+ */
646
+ export const ValidationHelpers = {
647
+ /**
648
+ * Create validation rules object
649
+ */
650
+ rules(rules: Record<string, string | ValidationRuleBuilder>): ValidationRules {
651
+ const result: ValidationRules = {}
652
+
653
+ for (const [field, fieldRules] of Object.entries(rules)) {
654
+ result[field] = fieldRules instanceof ValidationRuleBuilder
655
+ ? fieldRules.build()
656
+ : fieldRules
657
+ }
658
+
659
+ return result
660
+ },
661
+
662
+ /**
663
+ * Validate single value
664
+ */
665
+ async validateValue(value: any, rules: string, field = 'value'): Promise<string[]> {
666
+ const validator = new Validator()
667
+ const errors = await validator.validate({ [field]: value }, { [field]: rules })
668
+ return errors[field] || []
669
+ },
670
+
671
+ /**
672
+ * Check if value passes validation
673
+ */
674
+ async passes(value: any, rules: string): Promise<boolean> {
675
+ const errors = await this.validateValue(value, rules)
676
+ return errors.length === 0
677
+ },
678
+
679
+ /**
680
+ * Check if value fails validation
681
+ */
682
+ async fails(value: any, rules: string): Promise<boolean> {
683
+ return !(await this.passes(value, rules))
684
+ },
685
+ }