@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
@@ -1,685 +0,0 @@
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
- }