@morojs/moro 1.5.5 → 1.5.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 (70) hide show
  1. package/dist/core/config/config-manager.d.ts +44 -0
  2. package/dist/core/config/config-manager.js +114 -0
  3. package/dist/core/config/config-manager.js.map +1 -0
  4. package/dist/core/config/config-sources.d.ts +21 -0
  5. package/dist/core/config/config-sources.js +314 -0
  6. package/dist/core/config/config-sources.js.map +1 -0
  7. package/dist/core/config/config-validator.d.ts +21 -0
  8. package/dist/core/config/config-validator.js +737 -0
  9. package/dist/core/config/config-validator.js.map +1 -0
  10. package/dist/core/config/file-loader.d.ts +0 -5
  11. package/dist/core/config/file-loader.js +0 -171
  12. package/dist/core/config/file-loader.js.map +1 -1
  13. package/dist/core/config/index.d.ts +39 -10
  14. package/dist/core/config/index.js +66 -29
  15. package/dist/core/config/index.js.map +1 -1
  16. package/dist/core/config/schema.js +22 -31
  17. package/dist/core/config/schema.js.map +1 -1
  18. package/dist/core/config/utils.d.ts +9 -2
  19. package/dist/core/config/utils.js +19 -32
  20. package/dist/core/config/utils.js.map +1 -1
  21. package/dist/core/framework.d.ts +2 -7
  22. package/dist/core/framework.js +12 -5
  23. package/dist/core/framework.js.map +1 -1
  24. package/dist/core/http/http-server.d.ts +12 -0
  25. package/dist/core/http/http-server.js +56 -0
  26. package/dist/core/http/http-server.js.map +1 -1
  27. package/dist/core/http/router.d.ts +12 -0
  28. package/dist/core/http/router.js +114 -36
  29. package/dist/core/http/router.js.map +1 -1
  30. package/dist/core/logger/index.d.ts +1 -1
  31. package/dist/core/logger/index.js +2 -1
  32. package/dist/core/logger/index.js.map +1 -1
  33. package/dist/core/logger/logger.d.ts +9 -1
  34. package/dist/core/logger/logger.js +36 -3
  35. package/dist/core/logger/logger.js.map +1 -1
  36. package/dist/core/routing/index.d.ts +20 -0
  37. package/dist/core/routing/index.js +109 -11
  38. package/dist/core/routing/index.js.map +1 -1
  39. package/dist/moro.d.ts +7 -20
  40. package/dist/moro.js +97 -192
  41. package/dist/moro.js.map +1 -1
  42. package/dist/types/config.d.ts +39 -2
  43. package/dist/types/core.d.ts +22 -39
  44. package/dist/types/logger.d.ts +4 -0
  45. package/package.json +1 -1
  46. package/src/core/config/config-manager.ts +133 -0
  47. package/src/core/config/config-sources.ts +384 -0
  48. package/src/core/config/config-validator.ts +1035 -0
  49. package/src/core/config/file-loader.ts +0 -233
  50. package/src/core/config/index.ts +77 -32
  51. package/src/core/config/schema.ts +22 -31
  52. package/src/core/config/utils.ts +22 -29
  53. package/src/core/framework.ts +18 -11
  54. package/src/core/http/http-server.ts +66 -0
  55. package/src/core/http/router.ts +127 -38
  56. package/src/core/logger/index.ts +1 -0
  57. package/src/core/logger/logger.ts +43 -4
  58. package/src/core/routing/index.ts +116 -12
  59. package/src/moro.ts +105 -225
  60. package/src/types/config.ts +40 -2
  61. package/src/types/core.ts +32 -43
  62. package/src/types/logger.ts +6 -0
  63. package/dist/core/config/loader.d.ts +0 -7
  64. package/dist/core/config/loader.js +0 -269
  65. package/dist/core/config/loader.js.map +0 -1
  66. package/dist/core/config/validation.d.ts +0 -17
  67. package/dist/core/config/validation.js +0 -131
  68. package/dist/core/config/validation.js.map +0 -1
  69. package/src/core/config/loader.ts +0 -633
  70. package/src/core/config/validation.ts +0 -140
@@ -0,0 +1,1035 @@
1
+ /**
2
+ * Configuration Validator - Type-Safe Schema Validation
3
+ *
4
+ * This module provides runtime validation for configuration objects using
5
+ * simple TypeScript functions that match the type definitions exactly.
6
+ */
7
+
8
+ import { AppConfig } from '../../types/config';
9
+ import { createFrameworkLogger } from '../logger';
10
+
11
+ const logger = createFrameworkLogger('ConfigValidator');
12
+
13
+ /**
14
+ * Configuration validation error with detailed context
15
+ */
16
+ export class ConfigValidationError extends Error {
17
+ constructor(
18
+ public readonly field: string,
19
+ public readonly value: unknown,
20
+ public readonly expectedType: string,
21
+ message: string
22
+ ) {
23
+ super(`Configuration validation failed for '${field}': ${message}`);
24
+ this.name = 'ConfigValidationError';
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Validate and normalize a complete configuration object
30
+ * This ensures type safety and provides helpful error messages
31
+ */
32
+ export function validateConfig(config: any): AppConfig {
33
+ logger.debug('Validating configuration');
34
+
35
+ try {
36
+ const validatedConfig: AppConfig = {
37
+ server: validateServerConfig(config.server, 'server'),
38
+ serviceDiscovery: validateServiceDiscoveryConfig(config.serviceDiscovery, 'serviceDiscovery'),
39
+ database: validateDatabaseConfig(config.database, 'database'),
40
+ modules: validateModuleDefaultsConfig(config.modules, 'modules'),
41
+ logging: validateLoggingConfig(config.logging, 'logging'),
42
+ security: validateSecurityConfig(config.security, 'security'),
43
+ external: validateExternalServicesConfig(config.external, 'external'),
44
+ performance: validatePerformanceConfig(config.performance, 'performance'),
45
+ websocket: validateWebSocketConfig(config.websocket, 'websocket'),
46
+ };
47
+
48
+ logger.debug('Configuration validation successful');
49
+ return validatedConfig;
50
+ } catch (error) {
51
+ if (error instanceof ConfigValidationError) {
52
+ logger.error(`❌ Configuration validation failed for '${error.field}':`, error.message);
53
+
54
+ // Provide helpful hints
55
+ provideValidationHints(error);
56
+
57
+ throw error;
58
+ }
59
+
60
+ logger.error('❌ Unexpected configuration validation error:', String(error));
61
+ throw new Error(`Configuration validation failed: ${String(error)}`);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Validate server configuration
67
+ */
68
+ function validateServerConfig(config: any, path: string) {
69
+ if (!config || typeof config !== 'object') {
70
+ throw new ConfigValidationError(
71
+ path,
72
+ config,
73
+ 'object',
74
+ 'Server configuration must be an object'
75
+ );
76
+ }
77
+
78
+ return {
79
+ port: validatePort(config.port, `${path}.port`),
80
+ host: validateString(config.host, `${path}.host`),
81
+ maxConnections: validateNumber(config.maxConnections, `${path}.maxConnections`, { min: 1 }),
82
+ timeout: validateNumber(config.timeout, `${path}.timeout`, { min: 1000 }),
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Validate service discovery configuration
88
+ */
89
+ function validateServiceDiscoveryConfig(config: any, path: string) {
90
+ if (!config || typeof config !== 'object') {
91
+ throw new ConfigValidationError(
92
+ path,
93
+ config,
94
+ 'object',
95
+ 'Service discovery configuration must be an object'
96
+ );
97
+ }
98
+
99
+ return {
100
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
101
+ type: validateEnum(config.type, ['memory', 'consul', 'kubernetes'], `${path}.type`),
102
+ consulUrl: validateString(config.consulUrl, `${path}.consulUrl`),
103
+ kubernetesNamespace: validateString(config.kubernetesNamespace, `${path}.kubernetesNamespace`),
104
+ healthCheckInterval: validateNumber(config.healthCheckInterval, `${path}.healthCheckInterval`, {
105
+ min: 1000,
106
+ }),
107
+ retryAttempts: validateNumber(config.retryAttempts, `${path}.retryAttempts`, { min: 0 }),
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Validate database configuration
113
+ */
114
+ function validateDatabaseConfig(config: any, path: string) {
115
+ if (!config || typeof config !== 'object') {
116
+ throw new ConfigValidationError(
117
+ path,
118
+ config,
119
+ 'object',
120
+ 'Database configuration must be an object'
121
+ );
122
+ }
123
+
124
+ const result: any = {};
125
+
126
+ // Optional URL
127
+ if (config.url !== undefined) {
128
+ result.url = validateString(config.url, `${path}.url`);
129
+ }
130
+
131
+ // Optional Redis - only validate if present
132
+ if (config.redis !== undefined) {
133
+ result.redis = validateRedisConfig(config.redis, `${path}.redis`);
134
+ }
135
+
136
+ // Optional MySQL - only validate if present
137
+ if (config.mysql !== undefined) {
138
+ result.mysql = validateMySQLConfig(config.mysql, `${path}.mysql`);
139
+ }
140
+
141
+ // Optional PostgreSQL - only validate if present
142
+ if (config.postgresql !== undefined) {
143
+ result.postgresql = validatePostgreSQLConfig(config.postgresql, `${path}.postgresql`);
144
+ }
145
+
146
+ // Optional SQLite - only validate if present
147
+ if (config.sqlite !== undefined) {
148
+ result.sqlite = validateSQLiteConfig(config.sqlite, `${path}.sqlite`);
149
+ }
150
+
151
+ // Optional MongoDB - only validate if present
152
+ if (config.mongodb !== undefined) {
153
+ result.mongodb = validateMongoDBConfig(config.mongodb, `${path}.mongodb`);
154
+ }
155
+
156
+ return result;
157
+ }
158
+
159
+ /**
160
+ * Validate Redis configuration
161
+ */
162
+ function validateRedisConfig(config: any, path: string) {
163
+ if (!config || typeof config !== 'object') {
164
+ throw new ConfigValidationError(
165
+ path,
166
+ config,
167
+ 'object',
168
+ 'Redis configuration must be an object'
169
+ );
170
+ }
171
+
172
+ return {
173
+ url: validateString(config.url, `${path}.url`),
174
+ maxRetries: validateNumber(config.maxRetries, `${path}.maxRetries`, { min: 0 }),
175
+ retryDelay: validateNumber(config.retryDelay, `${path}.retryDelay`, { min: 0 }),
176
+ keyPrefix: validateString(config.keyPrefix, `${path}.keyPrefix`),
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Validate MySQL configuration
182
+ */
183
+ function validateMySQLConfig(config: any, path: string) {
184
+ if (!config || typeof config !== 'object') {
185
+ throw new ConfigValidationError(
186
+ path,
187
+ config,
188
+ 'object',
189
+ 'MySQL configuration must be an object'
190
+ );
191
+ }
192
+
193
+ const result: any = {
194
+ host: validateString(config.host, `${path}.host`),
195
+ port: validatePort(config.port, `${path}.port`),
196
+ connectionLimit: validateNumber(config.connectionLimit, `${path}.connectionLimit`, { min: 1 }),
197
+ acquireTimeout: validateNumber(config.acquireTimeout, `${path}.acquireTimeout`, { min: 1000 }),
198
+ timeout: validateNumber(config.timeout, `${path}.timeout`, { min: 1000 }),
199
+ };
200
+
201
+ // Optional fields
202
+ if (config.database !== undefined) {
203
+ result.database = validateString(config.database, `${path}.database`);
204
+ }
205
+ if (config.username !== undefined) {
206
+ result.username = validateString(config.username, `${path}.username`);
207
+ }
208
+ if (config.password !== undefined) {
209
+ result.password = validateString(config.password, `${path}.password`);
210
+ }
211
+
212
+ return result;
213
+ }
214
+
215
+ /**
216
+ * Validate PostgreSQL configuration
217
+ */
218
+ function validatePostgreSQLConfig(config: any, path: string) {
219
+ if (!config || typeof config !== 'object') {
220
+ throw new ConfigValidationError(
221
+ path,
222
+ config,
223
+ 'object',
224
+ 'PostgreSQL configuration must be an object'
225
+ );
226
+ }
227
+
228
+ const result: any = {
229
+ host: validateString(config.host, `${path}.host`),
230
+ port: validatePort(config.port, `${path}.port`),
231
+ connectionLimit: validateNumber(config.connectionLimit, `${path}.connectionLimit`, { min: 1 }),
232
+ };
233
+
234
+ // Optional fields
235
+ if (config.database !== undefined) {
236
+ result.database = validateString(config.database, `${path}.database`);
237
+ }
238
+ if (config.user !== undefined) {
239
+ result.user = validateString(config.user, `${path}.user`);
240
+ }
241
+ if (config.password !== undefined) {
242
+ result.password = validateString(config.password, `${path}.password`);
243
+ }
244
+ if (config.ssl !== undefined) {
245
+ result.ssl = validateBoolean(config.ssl, `${path}.ssl`);
246
+ }
247
+
248
+ return result;
249
+ }
250
+
251
+ /**
252
+ * Validate SQLite configuration
253
+ */
254
+ function validateSQLiteConfig(config: any, path: string) {
255
+ if (!config || typeof config !== 'object') {
256
+ throw new ConfigValidationError(
257
+ path,
258
+ config,
259
+ 'object',
260
+ 'SQLite configuration must be an object'
261
+ );
262
+ }
263
+
264
+ const result: any = {
265
+ filename: validateString(config.filename, `${path}.filename`),
266
+ };
267
+
268
+ // Optional fields
269
+ if (config.memory !== undefined) {
270
+ result.memory = validateBoolean(config.memory, `${path}.memory`);
271
+ }
272
+ if (config.verbose !== undefined) {
273
+ result.verbose = validateBoolean(config.verbose, `${path}.verbose`);
274
+ }
275
+
276
+ return result;
277
+ }
278
+
279
+ /**
280
+ * Validate MongoDB configuration
281
+ */
282
+ function validateMongoDBConfig(config: any, path: string) {
283
+ if (!config || typeof config !== 'object') {
284
+ throw new ConfigValidationError(
285
+ path,
286
+ config,
287
+ 'object',
288
+ 'MongoDB configuration must be an object'
289
+ );
290
+ }
291
+
292
+ const result: any = {};
293
+
294
+ // Either url or host+port
295
+ if (config.url !== undefined) {
296
+ result.url = validateString(config.url, `${path}.url`);
297
+ }
298
+ if (config.host !== undefined) {
299
+ result.host = validateString(config.host, `${path}.host`);
300
+ }
301
+ if (config.port !== undefined) {
302
+ result.port = validatePort(config.port, `${path}.port`);
303
+ }
304
+ if (config.database !== undefined) {
305
+ result.database = validateString(config.database, `${path}.database`);
306
+ }
307
+ if (config.username !== undefined) {
308
+ result.username = validateString(config.username, `${path}.username`);
309
+ }
310
+ if (config.password !== undefined) {
311
+ result.password = validateString(config.password, `${path}.password`);
312
+ }
313
+
314
+ return result;
315
+ }
316
+
317
+ /**
318
+ * Validate module defaults configuration
319
+ */
320
+ function validateModuleDefaultsConfig(config: any, path: string) {
321
+ if (!config || typeof config !== 'object') {
322
+ throw new ConfigValidationError(
323
+ path,
324
+ config,
325
+ 'object',
326
+ 'Module defaults configuration must be an object'
327
+ );
328
+ }
329
+
330
+ return {
331
+ cache: validateCacheConfig(config.cache, `${path}.cache`),
332
+ rateLimit: validateRateLimitConfig(config.rateLimit, `${path}.rateLimit`),
333
+ validation: validateValidationConfig(config.validation, `${path}.validation`),
334
+ };
335
+ }
336
+
337
+ /**
338
+ * Validate cache configuration
339
+ */
340
+ function validateCacheConfig(config: any, path: string) {
341
+ if (!config || typeof config !== 'object') {
342
+ throw new ConfigValidationError(
343
+ path,
344
+ config,
345
+ 'object',
346
+ 'Cache configuration must be an object'
347
+ );
348
+ }
349
+
350
+ return {
351
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
352
+ defaultTtl: validateNumber(config.defaultTtl, `${path}.defaultTtl`, { min: 0 }),
353
+ maxSize: validateNumber(config.maxSize, `${path}.maxSize`, { min: 1 }),
354
+ strategy: validateEnum(config.strategy, ['lru', 'lfu', 'fifo'], `${path}.strategy`),
355
+ };
356
+ }
357
+
358
+ /**
359
+ * Validate rate limit configuration
360
+ */
361
+ function validateRateLimitConfig(config: any, path: string) {
362
+ if (!config || typeof config !== 'object') {
363
+ throw new ConfigValidationError(
364
+ path,
365
+ config,
366
+ 'object',
367
+ 'Rate limit configuration must be an object'
368
+ );
369
+ }
370
+
371
+ return {
372
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
373
+ defaultRequests: validateNumber(config.defaultRequests, `${path}.defaultRequests`, { min: 1 }),
374
+ defaultWindow: validateNumber(config.defaultWindow, `${path}.defaultWindow`, { min: 1000 }),
375
+ skipSuccessfulRequests: validateBoolean(
376
+ config.skipSuccessfulRequests,
377
+ `${path}.skipSuccessfulRequests`
378
+ ),
379
+ skipFailedRequests: validateBoolean(config.skipFailedRequests, `${path}.skipFailedRequests`),
380
+ };
381
+ }
382
+
383
+ /**
384
+ * Validate validation configuration
385
+ */
386
+ function validateValidationConfig(config: any, path: string) {
387
+ if (!config || typeof config !== 'object') {
388
+ throw new ConfigValidationError(
389
+ path,
390
+ config,
391
+ 'object',
392
+ 'Validation configuration must be an object'
393
+ );
394
+ }
395
+
396
+ return {
397
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
398
+ stripUnknown: validateBoolean(config.stripUnknown, `${path}.stripUnknown`),
399
+ abortEarly: validateBoolean(config.abortEarly, `${path}.abortEarly`),
400
+ };
401
+ }
402
+
403
+ /**
404
+ * Validate logging configuration
405
+ */
406
+ function validateLoggingConfig(config: any, path: string) {
407
+ if (!config || typeof config !== 'object') {
408
+ throw new ConfigValidationError(
409
+ path,
410
+ config,
411
+ 'object',
412
+ 'Logging configuration must be an object'
413
+ );
414
+ }
415
+
416
+ return {
417
+ level: validateEnum(config.level, ['debug', 'info', 'warn', 'error', 'fatal'], `${path}.level`),
418
+ format: validateEnum(config.format, ['pretty', 'json', 'compact'], `${path}.format`),
419
+ enableColors: validateBoolean(config.enableColors, `${path}.enableColors`),
420
+ enableTimestamp: validateBoolean(config.enableTimestamp, `${path}.enableTimestamp`),
421
+ enableContext: validateBoolean(config.enableContext, `${path}.enableContext`),
422
+ outputs: validateLoggingOutputsConfig(config.outputs, `${path}.outputs`),
423
+ };
424
+ }
425
+
426
+ /**
427
+ * Validate logging outputs configuration
428
+ */
429
+ function validateLoggingOutputsConfig(config: any, path: string) {
430
+ if (!config || typeof config !== 'object') {
431
+ throw new ConfigValidationError(
432
+ path,
433
+ config,
434
+ 'object',
435
+ 'Logging outputs configuration must be an object'
436
+ );
437
+ }
438
+
439
+ return {
440
+ console: validateBoolean(config.console, `${path}.console`),
441
+ file: validateLoggingFileConfig(config.file, `${path}.file`),
442
+ webhook: validateLoggingWebhookConfig(config.webhook, `${path}.webhook`),
443
+ };
444
+ }
445
+
446
+ /**
447
+ * Validate logging file configuration
448
+ */
449
+ function validateLoggingFileConfig(config: any, path: string) {
450
+ if (!config || typeof config !== 'object') {
451
+ throw new ConfigValidationError(
452
+ path,
453
+ config,
454
+ 'object',
455
+ 'Logging file configuration must be an object'
456
+ );
457
+ }
458
+
459
+ return {
460
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
461
+ path: validateString(config.path, `${path}.path`),
462
+ maxSize: validateString(config.maxSize, `${path}.maxSize`),
463
+ maxFiles: validateNumber(config.maxFiles, `${path}.maxFiles`, { min: 1 }),
464
+ };
465
+ }
466
+
467
+ /**
468
+ * Validate logging webhook configuration
469
+ */
470
+ function validateLoggingWebhookConfig(config: any, path: string) {
471
+ if (!config || typeof config !== 'object') {
472
+ throw new ConfigValidationError(
473
+ path,
474
+ config,
475
+ 'object',
476
+ 'Logging webhook configuration must be an object'
477
+ );
478
+ }
479
+
480
+ const result: any = {
481
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
482
+ headers: validateObject(config.headers, `${path}.headers`),
483
+ };
484
+
485
+ // Optional URL
486
+ if (config.url !== undefined) {
487
+ result.url = validateString(config.url, `${path}.url`);
488
+ }
489
+
490
+ return result;
491
+ }
492
+
493
+ /**
494
+ * Validate security configuration
495
+ */
496
+ function validateSecurityConfig(config: any, path: string) {
497
+ if (!config || typeof config !== 'object') {
498
+ throw new ConfigValidationError(
499
+ path,
500
+ config,
501
+ 'object',
502
+ 'Security configuration must be an object'
503
+ );
504
+ }
505
+
506
+ return {
507
+ cors: validateCorsConfig(config.cors, `${path}.cors`),
508
+ helmet: validateHelmetConfig(config.helmet, `${path}.helmet`),
509
+ rateLimit: validateSecurityRateLimitConfig(config.rateLimit, `${path}.rateLimit`),
510
+ };
511
+ }
512
+
513
+ /**
514
+ * Validate CORS configuration
515
+ */
516
+ function validateCorsConfig(config: any, path: string) {
517
+ if (!config || typeof config !== 'object') {
518
+ throw new ConfigValidationError(path, config, 'object', 'CORS configuration must be an object');
519
+ }
520
+
521
+ return {
522
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
523
+ origin: validateCorsOrigin(config.origin, `${path}.origin`),
524
+ methods: validateStringArray(config.methods, `${path}.methods`),
525
+ allowedHeaders: validateStringArray(config.allowedHeaders, `${path}.allowedHeaders`),
526
+ credentials: validateBoolean(config.credentials, `${path}.credentials`),
527
+ };
528
+ }
529
+
530
+ /**
531
+ * Validate CORS origin (can be string, array, or boolean)
532
+ */
533
+ function validateCorsOrigin(value: any, path: string): string | string[] | boolean {
534
+ if (typeof value === 'boolean' || typeof value === 'string') {
535
+ return value;
536
+ }
537
+ if (Array.isArray(value)) {
538
+ return validateStringArray(value, path);
539
+ }
540
+ throw new ConfigValidationError(
541
+ path,
542
+ value,
543
+ 'string | string[] | boolean',
544
+ 'Must be a string, array of strings, or boolean'
545
+ );
546
+ }
547
+
548
+ /**
549
+ * Validate helmet configuration
550
+ */
551
+ function validateHelmetConfig(config: any, path: string) {
552
+ if (!config || typeof config !== 'object') {
553
+ throw new ConfigValidationError(
554
+ path,
555
+ config,
556
+ 'object',
557
+ 'Helmet configuration must be an object'
558
+ );
559
+ }
560
+
561
+ return {
562
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
563
+ contentSecurityPolicy: validateBoolean(
564
+ config.contentSecurityPolicy,
565
+ `${path}.contentSecurityPolicy`
566
+ ),
567
+ hsts: validateBoolean(config.hsts, `${path}.hsts`),
568
+ noSniff: validateBoolean(config.noSniff, `${path}.noSniff`),
569
+ frameguard: validateBoolean(config.frameguard, `${path}.frameguard`),
570
+ };
571
+ }
572
+
573
+ /**
574
+ * Validate security rate limit configuration
575
+ */
576
+ function validateSecurityRateLimitConfig(config: any, path: string) {
577
+ if (!config || typeof config !== 'object') {
578
+ throw new ConfigValidationError(
579
+ path,
580
+ config,
581
+ 'object',
582
+ 'Security rate limit configuration must be an object'
583
+ );
584
+ }
585
+
586
+ return {
587
+ global: validateGlobalRateLimitConfig(config.global, `${path}.global`),
588
+ };
589
+ }
590
+
591
+ /**
592
+ * Validate global rate limit configuration
593
+ */
594
+ function validateGlobalRateLimitConfig(config: any, path: string) {
595
+ if (!config || typeof config !== 'object') {
596
+ throw new ConfigValidationError(
597
+ path,
598
+ config,
599
+ 'object',
600
+ 'Global rate limit configuration must be an object'
601
+ );
602
+ }
603
+
604
+ return {
605
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
606
+ requests: validateNumber(config.requests, `${path}.requests`, { min: 1 }),
607
+ window: validateNumber(config.window, `${path}.window`, { min: 1000 }),
608
+ };
609
+ }
610
+
611
+ /**
612
+ * Validate external services configuration
613
+ */
614
+ function validateExternalServicesConfig(config: any, path: string) {
615
+ if (!config || typeof config !== 'object') {
616
+ throw new ConfigValidationError(
617
+ path,
618
+ config,
619
+ 'object',
620
+ 'External services configuration must be an object'
621
+ );
622
+ }
623
+
624
+ const result: any = {};
625
+
626
+ // Optional services - only validate if present
627
+ if (config.stripe !== undefined) {
628
+ result.stripe = validateStripeConfig(config.stripe, `${path}.stripe`);
629
+ }
630
+ if (config.paypal !== undefined) {
631
+ result.paypal = validatePayPalConfig(config.paypal, `${path}.paypal`);
632
+ }
633
+ if (config.smtp !== undefined) {
634
+ result.smtp = validateSMTPConfig(config.smtp, `${path}.smtp`);
635
+ }
636
+
637
+ return result;
638
+ }
639
+
640
+ /**
641
+ * Validate Stripe configuration
642
+ */
643
+ function validateStripeConfig(config: any, path: string) {
644
+ if (!config || typeof config !== 'object') {
645
+ throw new ConfigValidationError(
646
+ path,
647
+ config,
648
+ 'object',
649
+ 'Stripe configuration must be an object'
650
+ );
651
+ }
652
+
653
+ const result: any = {};
654
+
655
+ // Optional fields
656
+ if (config.secretKey !== undefined) {
657
+ result.secretKey = validateString(config.secretKey, `${path}.secretKey`);
658
+ }
659
+ if (config.publishableKey !== undefined) {
660
+ result.publishableKey = validateString(config.publishableKey, `${path}.publishableKey`);
661
+ }
662
+ if (config.webhookSecret !== undefined) {
663
+ result.webhookSecret = validateString(config.webhookSecret, `${path}.webhookSecret`);
664
+ }
665
+ if (config.apiVersion !== undefined) {
666
+ result.apiVersion = validateString(config.apiVersion, `${path}.apiVersion`);
667
+ } else {
668
+ result.apiVersion = '2023-10-16'; // Default API version
669
+ }
670
+
671
+ return result;
672
+ }
673
+
674
+ /**
675
+ * Validate PayPal configuration
676
+ */
677
+ function validatePayPalConfig(config: any, path: string) {
678
+ if (!config || typeof config !== 'object') {
679
+ throw new ConfigValidationError(
680
+ path,
681
+ config,
682
+ 'object',
683
+ 'PayPal configuration must be an object'
684
+ );
685
+ }
686
+
687
+ const result: any = {
688
+ environment: validateEnum(config.environment, ['sandbox', 'production'], `${path}.environment`),
689
+ };
690
+
691
+ // Optional fields
692
+ if (config.clientId !== undefined) {
693
+ result.clientId = validateString(config.clientId, `${path}.clientId`);
694
+ }
695
+ if (config.clientSecret !== undefined) {
696
+ result.clientSecret = validateString(config.clientSecret, `${path}.clientSecret`);
697
+ }
698
+ if (config.webhookId !== undefined) {
699
+ result.webhookId = validateString(config.webhookId, `${path}.webhookId`);
700
+ }
701
+
702
+ return result;
703
+ }
704
+
705
+ /**
706
+ * Validate SMTP configuration
707
+ */
708
+ function validateSMTPConfig(config: any, path: string) {
709
+ if (!config || typeof config !== 'object') {
710
+ throw new ConfigValidationError(path, config, 'object', 'SMTP configuration must be an object');
711
+ }
712
+
713
+ const result: any = {
714
+ port: validatePort(config.port, `${path}.port`),
715
+ secure: validateBoolean(config.secure, `${path}.secure`),
716
+ };
717
+
718
+ // Optional fields
719
+ if (config.host !== undefined) {
720
+ result.host = validateString(config.host, `${path}.host`);
721
+ }
722
+ if (config.username !== undefined) {
723
+ result.username = validateString(config.username, `${path}.username`);
724
+ }
725
+ if (config.password !== undefined) {
726
+ result.password = validateString(config.password, `${path}.password`);
727
+ }
728
+
729
+ return result;
730
+ }
731
+
732
+ /**
733
+ * Validate performance configuration
734
+ */
735
+ function validatePerformanceConfig(config: any, path: string) {
736
+ if (!config || typeof config !== 'object') {
737
+ throw new ConfigValidationError(
738
+ path,
739
+ config,
740
+ 'object',
741
+ 'Performance configuration must be an object'
742
+ );
743
+ }
744
+
745
+ return {
746
+ compression: validateCompressionConfig(config.compression, `${path}.compression`),
747
+ circuitBreaker: validateCircuitBreakerConfig(config.circuitBreaker, `${path}.circuitBreaker`),
748
+ clustering: validateClusteringConfig(config.clustering, `${path}.clustering`),
749
+ };
750
+ }
751
+
752
+ /**
753
+ * Validate compression configuration
754
+ */
755
+ function validateCompressionConfig(config: any, path: string) {
756
+ if (!config || typeof config !== 'object') {
757
+ throw new ConfigValidationError(
758
+ path,
759
+ config,
760
+ 'object',
761
+ 'Compression configuration must be an object'
762
+ );
763
+ }
764
+
765
+ return {
766
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
767
+ level: validateNumber(config.level, `${path}.level`, { min: 1, max: 9 }),
768
+ threshold: validateNumber(config.threshold, `${path}.threshold`, { min: 0 }),
769
+ };
770
+ }
771
+
772
+ /**
773
+ * Validate circuit breaker configuration
774
+ */
775
+ function validateCircuitBreakerConfig(config: any, path: string) {
776
+ if (!config || typeof config !== 'object') {
777
+ throw new ConfigValidationError(
778
+ path,
779
+ config,
780
+ 'object',
781
+ 'Circuit breaker configuration must be an object'
782
+ );
783
+ }
784
+
785
+ return {
786
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
787
+ failureThreshold: validateNumber(config.failureThreshold, `${path}.failureThreshold`, {
788
+ min: 1,
789
+ }),
790
+ resetTimeout: validateNumber(config.resetTimeout, `${path}.resetTimeout`, { min: 1000 }),
791
+ monitoringPeriod: validateNumber(config.monitoringPeriod, `${path}.monitoringPeriod`, {
792
+ min: 1000,
793
+ }),
794
+ };
795
+ }
796
+
797
+ /**
798
+ * Validate clustering configuration
799
+ */
800
+ function validateClusteringConfig(config: any, path: string) {
801
+ if (!config || typeof config !== 'object') {
802
+ throw new ConfigValidationError(
803
+ path,
804
+ config,
805
+ 'object',
806
+ 'Clustering configuration must be an object'
807
+ );
808
+ }
809
+
810
+ const result: any = {
811
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
812
+ };
813
+
814
+ // Workers can be number or 'auto'
815
+ if (typeof config.workers === 'string' && config.workers === 'auto') {
816
+ result.workers = 'auto';
817
+ } else {
818
+ result.workers = validateNumber(config.workers, `${path}.workers`, { min: 1 });
819
+ }
820
+
821
+ // Optional memoryPerWorkerGB
822
+ if (config.memoryPerWorkerGB !== undefined) {
823
+ result.memoryPerWorkerGB = validateNumber(
824
+ config.memoryPerWorkerGB,
825
+ `${path}.memoryPerWorkerGB`,
826
+ { min: 0.1 }
827
+ );
828
+ }
829
+
830
+ return result;
831
+ }
832
+
833
+ /**
834
+ * Validate WebSocket configuration
835
+ */
836
+ function validateWebSocketConfig(config: any, path: string) {
837
+ if (!config || typeof config !== 'object') {
838
+ throw new ConfigValidationError(
839
+ path,
840
+ config,
841
+ 'object',
842
+ 'WebSocket configuration must be an object'
843
+ );
844
+ }
845
+
846
+ const result: any = {
847
+ enabled: validateBoolean(config.enabled, `${path}.enabled`),
848
+ };
849
+
850
+ // Optional fields
851
+ if (config.adapter !== undefined) {
852
+ result.adapter = validateString(config.adapter, `${path}.adapter`);
853
+ }
854
+ if (config.compression !== undefined) {
855
+ result.compression = validateBoolean(config.compression, `${path}.compression`);
856
+ }
857
+ if (config.customIdGenerator !== undefined) {
858
+ result.customIdGenerator = config.customIdGenerator; // Function - no validation needed
859
+ }
860
+ if (config.options !== undefined) {
861
+ result.options = validateWebSocketOptions(config.options, `${path}.options`);
862
+ }
863
+
864
+ return result;
865
+ }
866
+
867
+ /**
868
+ * Validate WebSocket options
869
+ */
870
+ function validateWebSocketOptions(config: any, path: string) {
871
+ if (!config || typeof config !== 'object') {
872
+ throw new ConfigValidationError(path, config, 'object', 'WebSocket options must be an object');
873
+ }
874
+
875
+ const result: any = {};
876
+
877
+ if (config.cors !== undefined) {
878
+ result.cors = validateWebSocketCorsOptions(config.cors, `${path}.cors`);
879
+ }
880
+ if (config.path !== undefined) {
881
+ result.path = validateString(config.path, `${path}.path`);
882
+ }
883
+ if (config.maxPayloadLength !== undefined) {
884
+ result.maxPayloadLength = validateNumber(config.maxPayloadLength, `${path}.maxPayloadLength`, {
885
+ min: 1024,
886
+ });
887
+ }
888
+
889
+ return result;
890
+ }
891
+
892
+ /**
893
+ * Validate WebSocket CORS options
894
+ */
895
+ function validateWebSocketCorsOptions(config: any, path: string) {
896
+ if (!config || typeof config !== 'object') {
897
+ throw new ConfigValidationError(
898
+ path,
899
+ config,
900
+ 'object',
901
+ 'WebSocket CORS options must be an object'
902
+ );
903
+ }
904
+
905
+ const result: any = {};
906
+
907
+ if (config.origin !== undefined) {
908
+ result.origin = validateCorsOrigin(config.origin, `${path}.origin`);
909
+ }
910
+ if (config.credentials !== undefined) {
911
+ result.credentials = validateBoolean(config.credentials, `${path}.credentials`);
912
+ }
913
+
914
+ return result;
915
+ }
916
+
917
+ // Basic validation functions
918
+
919
+ function validatePort(value: any, path: string): number {
920
+ const num = Number(value);
921
+ if (isNaN(num) || num < 1 || num > 65535) {
922
+ throw new ConfigValidationError(
923
+ path,
924
+ value,
925
+ 'number (1-65535)',
926
+ 'Must be a number between 1 and 65535'
927
+ );
928
+ }
929
+ return num;
930
+ }
931
+
932
+ function validateBoolean(value: any, path: string): boolean {
933
+ if (value === 'true' || value === true) return true;
934
+ if (value === 'false' || value === false) return false;
935
+ if (value === '1' || value === 1) return true;
936
+ if (value === '0' || value === 0) return false;
937
+ throw new ConfigValidationError(
938
+ path,
939
+ value,
940
+ 'boolean',
941
+ 'Must be a boolean (true/false) or numeric (1/0)'
942
+ );
943
+ }
944
+
945
+ function validateNumber(
946
+ value: any,
947
+ path: string,
948
+ options: { min?: number; max?: number } = {}
949
+ ): number {
950
+ const num = Number(value);
951
+ if (isNaN(num)) {
952
+ throw new ConfigValidationError(path, value, 'number', 'Must be a valid number');
953
+ }
954
+ if (options.min !== undefined && num < options.min) {
955
+ throw new ConfigValidationError(
956
+ path,
957
+ value,
958
+ `number >= ${options.min}`,
959
+ `Must be at least ${options.min}`
960
+ );
961
+ }
962
+ if (options.max !== undefined && num > options.max) {
963
+ throw new ConfigValidationError(
964
+ path,
965
+ value,
966
+ `number <= ${options.max}`,
967
+ `Must be at most ${options.max}`
968
+ );
969
+ }
970
+ return num;
971
+ }
972
+
973
+ function validateString(value: any, path: string): string {
974
+ if (typeof value !== 'string') {
975
+ throw new ConfigValidationError(path, value, 'string', 'Must be a string');
976
+ }
977
+ return value;
978
+ }
979
+
980
+ function validateEnum<T extends string>(value: any, validValues: readonly T[], path: string): T {
981
+ const str = validateString(value, path);
982
+ if (!validValues.includes(str as T)) {
983
+ throw new ConfigValidationError(
984
+ path,
985
+ value,
986
+ `one of: ${validValues.join(', ')}`,
987
+ `Must be one of: ${validValues.join(', ')}`
988
+ );
989
+ }
990
+ return str as T;
991
+ }
992
+
993
+ function validateStringArray(value: any, path: string): string[] {
994
+ if (!Array.isArray(value)) {
995
+ // Try to parse comma-separated string
996
+ if (typeof value === 'string') {
997
+ return value
998
+ .split(',')
999
+ .map(s => s.trim())
1000
+ .filter(s => s.length > 0);
1001
+ }
1002
+ throw new ConfigValidationError(
1003
+ path,
1004
+ value,
1005
+ 'string[]',
1006
+ 'Must be an array or comma-separated string'
1007
+ );
1008
+ }
1009
+ return value.map((item, index) => validateString(item, `${path}[${index}]`));
1010
+ }
1011
+
1012
+ function validateObject(value: any, path: string): Record<string, string> {
1013
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1014
+ throw new ConfigValidationError(path, value, 'object', 'Must be an object');
1015
+ }
1016
+ return value;
1017
+ }
1018
+
1019
+ /**
1020
+ * Provide helpful validation hints based on the error
1021
+ */
1022
+ function provideValidationHints(error: ConfigValidationError): void {
1023
+ if (error.field.includes('port')) {
1024
+ logger.error(' 💡 Hint: Ports must be numbers between 1 and 65535');
1025
+ }
1026
+ if (error.field.includes('url')) {
1027
+ logger.error(' 💡 Hint: URLs must include protocol (http:// or https://)');
1028
+ }
1029
+ if (error.field.includes('environment')) {
1030
+ logger.error(' 💡 Hint: NODE_ENV must be one of: development, staging, production');
1031
+ }
1032
+ if (error.field.includes('level')) {
1033
+ logger.error(' 💡 Hint: Log level must be one of: debug, info, warn, error, fatal');
1034
+ }
1035
+ }