@morojs/moro 1.5.17 → 1.6.1

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