Spaces:
Paused
Paused
File size: 12,223 Bytes
21cac8a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | const fs = require('fs').promises;
const path = require('path');
const Joi = require('joi');
const configSchema = require('./schema');
class ConfigManager {
constructor() {
this.config = null;
this.environment = process.env.NODE_ENV || 'development';
this.configCache = new Map();
this.watchers = new Map();
this.validationErrors = [];
this.isInitialized = false;
}
/**
* Initialize the configuration manager
*/
async initialize() {
if (this.isInitialized) {
return this.config;
}
try {
// Load base configuration
const baseConfig = await this.loadBaseConfig();
// Load environment-specific configuration
const envConfig = await this.loadEnvironmentConfig();
// Merge configurations (environment overrides base)
const mergedConfig = this.mergeConfigs(baseConfig, envConfig);
// Load environment variables
const envVarsConfig = this.loadEnvironmentVariables();
// Final merge (env vars override everything)
const finalConfig = this.mergeConfigs(mergedConfig, envVarsConfig);
// Validate configuration
await this.validateConfig(finalConfig);
this.config = finalConfig;
this.isInitialized = true;
console.log(`Configuration loaded successfully for environment: ${this.environment}`);
return this.config;
} catch (error) {
console.error('Failed to initialize configuration:', error);
throw error;
}
}
/**
* Load base configuration
*/
async loadBaseConfig() {
const configPath = path.join(__dirname, 'default.json');
try {
const configFile = await fs.readFile(configPath, 'utf8');
return JSON.parse(configFile);
} catch (error) {
if (error.code === 'ENOENT') {
console.warn('Default configuration file not found, using schema defaults');
return {};
}
throw new Error(`Failed to load base configuration: ${error.message}`);
}
}
/**
* Load environment-specific configuration
*/
async loadEnvironmentConfig() {
const configPath = path.join(__dirname, `${this.environment}.json`);
try {
const configFile = await fs.readFile(configPath, 'utf8');
return JSON.parse(configFile);
} catch (error) {
if (error.code === 'ENOENT') {
console.warn(`Environment configuration file not found: ${configPath}`);
return {};
}
throw new Error(`Failed to load environment configuration: ${error.message}`);
}
}
/**
* Load configuration from environment variables
*/
loadEnvironmentVariables() {
const envConfig = {};
// Map environment variables to configuration structure
const envMappings = {
// Server
'PORT': 'server.port',
'HOST': 'server.host',
'NODE_ENV': 'server.environment',
'CORS_ENABLED': 'server.corsEnabled',
'RATE_LIMIT_ENABLED': 'server.rateLimitEnabled',
'RATE_LIMIT_WINDOW_MS': 'server.rateLimitWindowMs',
'RATE_LIMIT_MAX_REQUESTS': 'server.rateLimitMaxRequests',
// Database
'DATABASE_TYPE': 'database.type',
'DATABASE_PATH': 'database.path',
'DATABASE_HOST': 'database.host',
'DATABASE_PORT': 'database.port',
'DATABASE_NAME': 'database.name',
'DATABASE_USERNAME': 'database.username',
'DATABASE_PASSWORD': 'database.password',
// AI Services
'GEMINI_API_KEY': 'ai.gemini.apiKey',
'GEMINI_MODEL': 'ai.gemini.model',
'GEMINI_MAX_RETRIES': 'ai.gemini.maxRetries',
'GEMINI_TIMEOUT_MS': 'ai.gemini.timeoutMs',
// Analysis
'MAX_CONCURRENT_ANALYSES': 'analysis.maxConcurrentAnalyses',
'ANALYSIS_TIMEOUT_MS': 'analysis.timeoutMs',
'MAX_STUCK_TIME_MS': 'analysis.maxStuckTimeMs',
'CLEANUP_INTERVAL_MS': 'analysis.cleanupIntervalMs',
'ENABLE_ACCESSIBILITY': 'analysis.enableAccessibility',
'ENABLE_VISUAL_ANALYSIS': 'analysis.enableVisualAnalysis',
'ENABLE_AI_CRITIQUE': 'analysis.enableAICritique',
// Screenshots
'SCREENSHOT_STORAGE_PATH': 'screenshots.storagePath',
'SCREENSHOT_TIMEOUT_MS': 'screenshots.timeoutMs',
'SCREENSHOT_WAIT_FOR_MS': 'screenshots.waitForMs',
// Browser
'BROWSER_POOL_SIZE': 'browser.poolSize',
'BROWSER_MAX_IDLE_TIME_MS': 'browser.maxIdleTimeMs',
'BROWSER_MAX_LIFETIME_MS': 'browser.maxLifetimeMs',
'BROWSER_HEADLESS': 'browser.headless',
// Logging
'LOG_LEVEL': 'logging.level',
'LOG_ENABLE_CONSOLE': 'logging.enableConsole',
'LOG_ENABLE_FILE': 'logging.enableFile',
'LOG_FILE_PATH': 'logging.filePath',
// Features
'FEATURE_ACCESSIBILITY_ANALYSIS': 'features.accessibilityAnalysis',
'FEATURE_VISUAL_DESIGN_ANALYSIS': 'features.visualDesignAnalysis',
'FEATURE_AI_CRITIQUE': 'features.aiCritique',
'FEATURE_QUEUE_SYSTEM': 'features.queueSystem',
'FEATURE_CACHING': 'features.caching',
// Redis/Queue
'REDIS_HOST': 'queue.redis.host',
'REDIS_PORT': 'queue.redis.port',
'REDIS_PASSWORD': 'queue.redis.password',
'REDIS_DB': 'queue.redis.db'
};
// Process environment variables
for (const [envVar, configPath] of Object.entries(envMappings)) {
const value = process.env[envVar];
if (value !== undefined) {
this.setNestedValue(envConfig, configPath, this.parseEnvValue(value));
}
}
return envConfig;
}
/**
* Parse environment variable value to appropriate type
*/
parseEnvValue(value) {
// Boolean
if (value.toLowerCase() === 'true') return true;
if (value.toLowerCase() === 'false') return false;
// Number
if (/^\d+$/.test(value)) return parseInt(value, 10);
if (/^\d+\.\d+$/.test(value)) return parseFloat(value);
// Array (comma-separated)
if (value.includes(',')) {
return value.split(',').map(item => item.trim());
}
// String
return value;
}
/**
* Set nested object value using dot notation
*/
setNestedValue(obj, path, value) {
const keys = path.split('.');
let current = obj;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (!(key in current) || typeof current[key] !== 'object') {
current[key] = {};
}
current = current[key];
}
current[keys[keys.length - 1]] = value;
}
/**
* Merge two configuration objects
*/
mergeConfigs(base, override) {
const result = JSON.parse(JSON.stringify(base));
function merge(target, source) {
for (const key in source) {
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
if (!target[key] || typeof target[key] !== 'object') {
target[key] = {};
}
merge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
merge(result, override);
return result;
}
/**
* Validate configuration against schema
*/
async validateConfig(config) {
try {
const { error, value } = configSchema.validate(config, {
allowUnknown: false,
abortEarly: false,
stripUnknown: true
});
if (error) {
this.validationErrors = error.details.map(detail => ({
path: detail.path.join('.'),
message: detail.message,
value: detail.context?.value
}));
const errorMsg = `Configuration validation failed:\n${this.validationErrors
.map(err => ` - ${err.path}: ${err.message}`)
.join('\n')}`;
throw new Error(errorMsg);
}
// Use validated and default-filled configuration
Object.assign(config, value);
} catch (error) {
console.error('Configuration validation error:', error.message);
throw error;
}
}
/**
* Get configuration value by path
*/
get(path, defaultValue = undefined) {
if (!this.isInitialized) {
throw new Error('Configuration not initialized. Call initialize() first.');
}
if (!path) {
return this.config;
}
const keys = path.split('.');
let current = this.config;
for (const key of keys) {
if (current && typeof current === 'object' && key in current) {
current = current[key];
} else {
return defaultValue;
}
}
return current;
}
/**
* Check if a feature is enabled
*/
isFeatureEnabled(featureName) {
return this.get(`features.${featureName}`, false);
}
/**
* Get database configuration
*/
getDatabaseConfig() {
return this.get('database');
}
/**
* Get server configuration
*/
getServerConfig() {
return this.get('server');
}
/**
* Get AI service configuration
*/
getAIConfig() {
return this.get('ai');
}
/**
* Get analysis configuration
*/
getAnalysisConfig() {
return this.get('analysis');
}
/**
* Get browser configuration
*/
getBrowserConfig() {
return this.get('browser');
}
/**
* Get logging configuration
*/
getLoggingConfig() {
return this.get('logging');
}
/**
* Get health check configuration
*/
getHealthConfig() {
return this.get('health');
}
/**
* Get security configuration
*/
getSecurityConfig() {
return this.get('security');
}
/**
* Watch configuration file for changes
*/
async watchConfig(callback) {
if (!this.isFeatureEnabled('configReloading')) {
return;
}
const configFiles = [
path.join(__dirname, 'default.json'),
path.join(__dirname, `${this.environment}.json`)
];
for (const filePath of configFiles) {
try {
const watcher = fs.watch(filePath, async (eventType) => {
if (eventType === 'change') {
console.log(`Configuration file changed: ${filePath}`);
try {
await this.reload();
if (callback) callback(this.config);
} catch (error) {
console.error('Failed to reload configuration:', error);
}
}
});
this.watchers.set(filePath, watcher);
} catch (error) {
console.warn(`Cannot watch configuration file: ${filePath}`);
}
}
}
/**
* Reload configuration
*/
async reload() {
this.isInitialized = false;
this.config = null;
this.configCache.clear();
await this.initialize();
}
/**
* Stop watching configuration files
*/
stopWatching() {
for (const [filePath, watcher] of this.watchers) {
try {
watcher.close();
console.log(`Stopped watching: ${filePath}`);
} catch (error) {
console.warn(`Error closing watcher for ${filePath}:`, error);
}
}
this.watchers.clear();
}
/**
* Validate required environment variables
*/
validateRequiredEnvVars() {
const required = [
'GEMINI_API_KEY'
];
const missing = required.filter(envVar => !process.env[envVar]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
/**
* Get current environment
*/
getEnvironment() {
return this.environment;
}
/**
* Check if running in development mode
*/
isDevelopment() {
return this.environment === 'development';
}
/**
* Check if running in production mode
*/
isProduction() {
return this.environment === 'production';
}
/**
* Get configuration summary for logging
*/
getSummary() {
if (!this.isInitialized) {
return { status: 'not_initialized' };
}
return {
environment: this.environment,
server: {
port: this.get('server.port'),
host: this.get('server.host')
},
features: this.get('features'),
database: {
type: this.get('database.type'),
path: this.get('database.path')
},
analysis: {
maxConcurrent: this.get('analysis.maxConcurrentAnalyses'),
timeoutMs: this.get('analysis.timeoutMs')
}
};
}
}
// Create singleton instance
const configManager = new ConfigManager();
module.exports = configManager; |