@tamyla/clodo-framework 3.1.21 → 3.1.23

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 (150) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +283 -1
  3. package/dist/{bin → cli}/clodo-service.js +47 -15
  4. package/dist/cli/commands/assess.js +183 -0
  5. package/dist/{bin → cli}/commands/create.js +5 -5
  6. package/dist/{bin → cli}/commands/deploy.js +122 -90
  7. package/dist/{bin → cli}/commands/diagnose.js +5 -5
  8. package/dist/cli/commands/helpers/deployment-ui.js +138 -0
  9. package/dist/cli/commands/helpers/deployment-verification.js +250 -0
  10. package/dist/cli/commands/helpers/error-recovery.js +80 -0
  11. package/dist/cli/commands/helpers/resource-detection.js +113 -0
  12. package/dist/{bin → cli}/commands/helpers.js +0 -28
  13. package/dist/cli/commands/init-config.js +57 -0
  14. package/dist/{bin → cli}/commands/update.js +5 -5
  15. package/dist/{bin → cli}/commands/validate.js +5 -5
  16. package/dist/cli/security-cli.js +118 -0
  17. package/dist/config/FeatureManager.js +6 -0
  18. package/dist/config/clodo-create.example.json +26 -0
  19. package/dist/config/clodo-deploy.example.json +41 -0
  20. package/dist/config/clodo-update.example.json +46 -0
  21. package/dist/config/clodo-validate.example.json +41 -0
  22. package/dist/config/customers/template/development.env.template +37 -0
  23. package/dist/config/customers/template/production.env.template +39 -0
  24. package/dist/config/customers/template/staging.env.template +37 -0
  25. package/dist/config/customers.js +28 -26
  26. package/dist/config/domain-examples/README.md +464 -0
  27. package/dist/config/domain-examples/environment-mapped.json +168 -0
  28. package/dist/config/domain-examples/multi-domain.json +144 -0
  29. package/dist/config/domain-examples/single-domain.json +50 -0
  30. package/dist/config/examples +12 -0
  31. package/dist/config/features.js +61 -0
  32. package/dist/config/staging-deployment.json +60 -0
  33. package/dist/config/validation-config.json +347 -0
  34. package/dist/deployment/wrangler-deployer.js +1 -1
  35. package/dist/{bin → lib}/deployment/modules/DeploymentOrchestrator.js +2 -2
  36. package/dist/{bin → lib}/deployment/modules/EnvironmentManager.js +2 -2
  37. package/dist/lib/deployment/orchestration/EnterpriseOrchestrator.js +21 -0
  38. package/dist/lib/shared/cache/configuration-cache.js +82 -0
  39. package/dist/{bin → lib}/shared/cloudflare/domain-discovery.js +1 -1
  40. package/dist/{bin → lib}/shared/cloudflare/domain-manager.js +1 -1
  41. package/dist/{bin → lib}/shared/cloudflare/index.js +1 -1
  42. package/dist/{bin → lib}/shared/cloudflare/ops.js +10 -8
  43. package/dist/{bin → lib}/shared/config/ConfigurationManager.js +23 -1
  44. package/dist/{bin → lib}/shared/config/command-config-manager.js +19 -3
  45. package/dist/{bin → lib}/shared/config/index.js +1 -1
  46. package/dist/{bin → lib}/shared/deployment/credential-collector.js +30 -7
  47. package/dist/lib/shared/deployment/index.js +10 -0
  48. package/dist/lib/shared/deployment/rollback-manager.js +7 -0
  49. package/dist/lib/shared/deployment/utilities/d1-error-recovery.js +177 -0
  50. package/dist/{bin → lib}/shared/deployment/validator.js +40 -10
  51. package/dist/lib/shared/deployment/workflows/deployment-summary.js +214 -0
  52. package/dist/lib/shared/deployment/workflows/interactive-confirmation.js +188 -0
  53. package/dist/lib/shared/deployment/workflows/interactive-database-workflow.js +234 -0
  54. package/dist/lib/shared/deployment/workflows/interactive-domain-info-gatherer.js +240 -0
  55. package/dist/lib/shared/deployment/workflows/interactive-secret-workflow.js +228 -0
  56. package/dist/lib/shared/deployment/workflows/interactive-testing-workflow.js +235 -0
  57. package/dist/lib/shared/deployment/workflows/interactive-validation.js +218 -0
  58. package/dist/lib/shared/error-handling/error-classifier.js +46 -0
  59. package/dist/{bin → lib}/shared/monitoring/health-checker.js +129 -1
  60. package/dist/{bin → lib}/shared/monitoring/memory-manager.js +17 -6
  61. package/dist/{bin → lib}/shared/routing/domain-router.js +1 -1
  62. package/dist/lib/shared/utils/deployment-validator.js +97 -0
  63. package/dist/{bin → lib}/shared/utils/formatters.js +10 -0
  64. package/dist/{bin → lib}/shared/utils/index.js +13 -1
  65. package/dist/{bin → lib}/shared/utils/interactive-prompts.js +34 -18
  66. package/dist/{bin → lib}/shared/utils/progress-manager.js +2 -2
  67. package/dist/lib/shared/utils/progress-spinner.js +53 -0
  68. package/dist/lib/shared/utils/sensitive-redactor.js +91 -0
  69. package/dist/{bin → lib}/shared/validation/ValidationRegistry.js +1 -1
  70. package/dist/migration/MigrationAdapters.js +50 -4
  71. package/dist/orchestration/cross-domain-coordinator.js +5 -5
  72. package/dist/orchestration/multi-domain-orchestrator.js +63 -22
  73. package/dist/security/index.js +2 -2
  74. package/dist/security/patterns/insecure-patterns.js +1 -1
  75. package/dist/service-management/ConfirmationEngine.js +1 -1
  76. package/dist/service-management/ErrorTracker.js +1 -1
  77. package/dist/service-management/InputCollector.js +1 -1
  78. package/dist/service-management/ServiceCreator.js +11 -255
  79. package/dist/service-management/ServiceOrchestrator.js +0 -2
  80. package/dist/service-management/generators/testing/UnitTestsGenerator.js +4 -4
  81. package/dist/service-management/index.js +1 -1
  82. package/dist/utils/cloudflare/ops.js +1 -1
  83. package/dist/utils/constants.js +102 -0
  84. package/dist/utils/deployment/wrangler-config-manager.js +215 -48
  85. package/dist/utils/file-manager.js +1 -1
  86. package/dist/utils/formatters.js +1 -1
  87. package/dist/utils/framework-config.js +2 -2
  88. package/dist/utils/interactive-prompts.js +10 -59
  89. package/dist/utils/logger.js +1 -1
  90. package/dist/version/VersionDetector.js +99 -9
  91. package/dist/worker/integration.js +1 -1
  92. package/package.json +10 -10
  93. package/dist/bin/clodo-service-old.js +0 -868
  94. package/dist/bin/clodo-service-test.js +0 -10
  95. package/dist/bin/commands/assess.js +0 -91
  96. package/dist/bin/database/enterprise-db-manager.js +0 -457
  97. package/dist/bin/deployment/enterprise-deploy.js +0 -877
  98. package/dist/bin/deployment/master-deploy.js +0 -1376
  99. package/dist/bin/deployment/modular-enterprise-deploy.js +0 -466
  100. package/dist/bin/deployment/orchestration/EnterpriseOrchestrator.js +0 -401
  101. package/dist/bin/deployment/test-interactive-utils.js +0 -66
  102. package/dist/bin/portfolio/portfolio-manager.js +0 -487
  103. package/dist/bin/security/security-cli.js +0 -108
  104. package/dist/bin/service-management/create-service.js +0 -122
  105. package/dist/bin/service-management/init-service.js +0 -79
  106. package/dist/bin/shared/deployment/index.js +0 -10
  107. package/dist/bin/shared/deployment/rollback-manager.js +0 -523
  108. package/dist/deployment/orchestration/EnterpriseOrchestrator.js +0 -401
  109. package/dist/service-management/ServiceInitializer.js +0 -453
  110. /package/dist/{bin → lib}/database/deployment-db-manager.js +0 -0
  111. /package/dist/{bin → lib}/database/wrangler-d1-manager.js +0 -0
  112. /package/dist/{bin → lib}/deployment/modules/DeploymentConfiguration.js +0 -0
  113. /package/dist/{bin → lib}/deployment/modules/MonitoringIntegration.js +0 -0
  114. /package/dist/{bin → lib}/deployment/modules/ValidationManager.js +0 -0
  115. /package/dist/{bin → lib}/deployment/orchestration/BaseDeploymentOrchestrator.js +0 -0
  116. /package/dist/{bin → lib}/deployment/orchestration/PortfolioOrchestrator.js +0 -0
  117. /package/dist/{bin → lib}/deployment/orchestration/SingleServiceOrchestrator.js +0 -0
  118. /package/dist/{bin → lib}/deployment/orchestration/UnifiedDeploymentOrchestrator.js +0 -0
  119. /package/dist/{bin → lib}/shared/config/cache.js +0 -0
  120. /package/dist/{bin → lib}/shared/config/cloudflare-service-validator.js +0 -0
  121. /package/dist/{bin → lib}/shared/config/manager.js +0 -0
  122. /package/dist/{bin → lib}/shared/config/manifest-loader.js +0 -0
  123. /package/dist/{bin → lib}/shared/database/connection-manager.js +0 -0
  124. /package/dist/{bin → lib}/shared/database/index.js +0 -0
  125. /package/dist/{bin → lib}/shared/database/orchestrator.js +0 -0
  126. /package/dist/{bin → lib}/shared/deployment/auditor.js +0 -0
  127. /package/dist/{bin → lib}/shared/index.js +0 -0
  128. /package/dist/{bin → lib}/shared/logging/Logger.js +0 -0
  129. /package/dist/{bin → lib}/shared/monitoring/index.js +0 -0
  130. /package/dist/{bin → lib}/shared/monitoring/production-monitor.js +0 -0
  131. /package/dist/{bin → lib}/shared/production-tester/api-tester.js +0 -0
  132. /package/dist/{bin → lib}/shared/production-tester/auth-tester.js +0 -0
  133. /package/dist/{bin → lib}/shared/production-tester/core.js +0 -0
  134. /package/dist/{bin → lib}/shared/production-tester/database-tester.js +0 -0
  135. /package/dist/{bin → lib}/shared/production-tester/index.js +0 -0
  136. /package/dist/{bin → lib}/shared/production-tester/load-tester.js +0 -0
  137. /package/dist/{bin → lib}/shared/production-tester/performance-tester.js +0 -0
  138. /package/dist/{bin → lib}/shared/security/api-token-manager.js +0 -0
  139. /package/dist/{bin → lib}/shared/security/index.js +0 -0
  140. /package/dist/{bin → lib}/shared/security/secret-generator.js +0 -0
  141. /package/dist/{bin → lib}/shared/security/secure-token-manager.js +0 -0
  142. /package/dist/{bin → lib}/shared/utils/ErrorHandler.js +0 -0
  143. /package/dist/{bin → lib}/shared/utils/cli-options.js +0 -0
  144. /package/dist/{bin → lib}/shared/utils/config-loader.js +0 -0
  145. /package/dist/{bin → lib}/shared/utils/error-recovery.js +0 -0
  146. /package/dist/{bin → lib}/shared/utils/file-manager.js +0 -0
  147. /package/dist/{bin → lib}/shared/utils/graceful-shutdown-manager.js +0 -0
  148. /package/dist/{bin → lib}/shared/utils/interactive-utils.js +0 -0
  149. /package/dist/{bin → lib}/shared/utils/output-formatter.js +0 -0
  150. /package/dist/{bin → lib}/shared/utils/rate-limiter.js +0 -0
@@ -1,1376 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Enhanced Enterprise Master Deployment Script
5
- *
6
- * Next-generation deployment system powered by enterprise modules.
7
- * Provides bulletproof reliability, comprehensive validation, and portfolio management.
8
- *
9
- * Enterprise Features:
10
- * - Multi-domain orchestration and coordination
11
- * - Advanced validation with comprehensive checks
12
- * - Automatic rollback and recovery
13
- * - Runtime configuration discovery
14
- * - Enterprise-grade audit and logging
15
- * - Smart configuration caching
16
- * - Production testing suite
17
- * - Cross-domain compatibility
18
- * - Performance monitoring
19
- * - Compliance tracking
20
- *
21
- * @version 2.0.0 - Enterprise Edition
22
- */
23
-
24
- // Enterprise module imports - organized shared modules
25
- import { askUser, askYesNo, askChoice, closePrompts } from '../shared/utils/interactive-prompts.js';
26
- import { ConfigurationCacheManager } from '../shared/config/cache.js';
27
- import { EnhancedSecretManager, generateSecrets, saveSecrets, distributeSecrets } from '../shared/security/secret-generator.js';
28
- import { exec } from 'child_process';
29
- import { promisify } from 'util';
30
- import { join } from 'path';
31
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
32
- const execAsync = promisify(exec);
33
- import { MultiDomainOrchestrator } from "../../orchestration/multi-domain-orchestrator.js";
34
- import { CrossDomainCoordinator } from "../../orchestration/cross-domain-coordinator.js";
35
- import { RollbackManager } from '../shared/deployment/rollback-manager.js';
36
- import { ProductionTester } from '../shared/production-tester/index.js';
37
- import { DeploymentAuditor } from '../shared/deployment/auditor.js';
38
- import { DeploymentValidator } from '../shared/deployment/validator.js';
39
- import { DomainDiscovery } from '../shared/cloudflare/domain-discovery.js';
40
- import { DatabaseOrchestrator } from "../../database/database-orchestrator.js";
41
-
42
- // New modular architecture components
43
- import { DeploymentConfiguration } from './modules/DeploymentConfiguration.js';
44
- import { EnvironmentManager } from './modules/EnvironmentManager.js';
45
- import { ValidationManager } from './modules/ValidationManager.js';
46
- import { MonitoringIntegration } from './modules/MonitoringIntegration.js';
47
- import { DeploymentOrchestrator as ModularDeploymentOrchestrator } from './modules/DeploymentOrchestrator.js';
48
-
49
- // Updated imports for fixed shared module structure
50
- import { checkAuth, authenticate, workerExists, deployWorker, deploySecret, databaseExists, createDatabase, getDatabaseId, runMigrations, validatePrerequisites, listDatabases, deleteDatabase, executeSql } from '../shared/cloudflare/ops.js';
51
- import { waitForDeployment, enhancedComprehensiveHealthCheck, checkHealth } from '../shared/monitoring/health-checker.js';
52
- import { updateWranglerConfig, backupConfig } from '../shared/config/manager.js';
53
- class EnterpriseInteractiveDeployer {
54
- constructor() {
55
- // Load framework configuration for organized paths
56
- this.frameworkConfig = null;
57
- this.frameworkPaths = null;
58
-
59
- // New modular components - initialized lazily
60
- this.modularComponents = {
61
- config: null,
62
- // DeploymentConfiguration
63
- environment: null,
64
- // EnvironmentManager
65
- validation: null,
66
- // ValidationManager
67
- monitoring: null,
68
- // MonitoringIntegration
69
- orchestrator: null // ModularDeploymentOrchestrator
70
- };
71
- this.config = {
72
- // Basic deployment config
73
- domain: null,
74
- environment: null,
75
- deploymentMode: 'single',
76
- // 'single', 'multi-domain', 'portfolio'
77
-
78
- // Worker configuration
79
- worker: {
80
- name: null,
81
- url: null
82
- },
83
- // Database configuration
84
- database: {
85
- name: null,
86
- id: null,
87
- createNew: false,
88
- enableMigrations: true
89
- },
90
- // Secret configuration
91
- secrets: {
92
- generateNew: true,
93
- useEnterpriseCoordination: true,
94
- crossDomainSharing: false,
95
- keys: {}
96
- },
97
- // Deployment options
98
- deployment: {
99
- runTests: true,
100
- skipExisting: false,
101
- enableRollback: true,
102
- validationLevel: 'comprehensive',
103
- // 'basic', 'standard', 'comprehensive'
104
- auditLevel: 'detailed' // 'minimal', 'standard', 'detailed', 'verbose'
105
- },
106
- // Enterprise features
107
- enterprise: {
108
- enableOrchestration: true,
109
- enableCrossDomainCoordination: false,
110
- enableAdvancedValidation: true,
111
- enableProductionTesting: true,
112
- enableConfigCaching: true,
113
- enableAuditLogging: true
114
- }
115
- };
116
- this.state = {
117
- deploymentId: this.generateId(),
118
- startTime: new Date(),
119
- rollbackActions: [],
120
- currentPhase: 'initialization',
121
- enterpriseModules: null
122
- };
123
-
124
- // Initialize enterprise modules
125
- this.initializeEnterpriseModules();
126
- }
127
- generateId() {
128
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
129
- const random = Math.random().toString(36).substr(2, 9);
130
- return `deploy-enterprise-${timestamp}-${random}`;
131
- }
132
-
133
- /**
134
- * Initialize all enterprise modules for deployment
135
- */
136
- initializeEnterpriseModules() {
137
- console.log('🚀 Initializing Enterprise Deployment System...');
138
- this.state.enterpriseModules = {
139
- orchestrator: new MultiDomainOrchestrator({
140
- enableInteractiveMode: true,
141
- deploymentId: this.state.deploymentId
142
- }),
143
- validator: new DeploymentValidator({
144
- validationLevel: this.config.deployment.validationLevel,
145
- interactiveMode: true
146
- }),
147
- rollbackManager: new RollbackManager({
148
- autoRollbackEnabled: this.config.deployment.enableRollback,
149
- interactiveConfirmation: true
150
- }),
151
- domainDiscovery: new DomainDiscovery({
152
- enableInteractiveConfig: true,
153
- cacheDiscoveredConfigs: true
154
- }),
155
- databaseOrchestrator: new DatabaseOrchestrator({
156
- enableSafeMode: true,
157
- requireConfirmation: true
158
- }),
159
- secretManager: new EnhancedSecretManager({
160
- interactiveMode: true,
161
- crossDomainCoordination: this.config.secrets.crossDomainSharing
162
- }),
163
- productionTester: new ProductionTester({
164
- interactiveReporting: true,
165
- comprehensiveTests: this.config.deployment.runTests
166
- }),
167
- auditor: new DeploymentAuditor({
168
- auditLevel: this.config.deployment.auditLevel,
169
- interactiveMode: true
170
- }),
171
- configCache: new ConfigurationCacheManager({
172
- enableInteractiveDiscovery: true,
173
- autoCache: true
174
- }),
175
- coordinator: null // Will be initialized if multi-domain mode is selected
176
- };
177
- console.log('✅ Enterprise modules initialized');
178
- }
179
- async run() {
180
- // Initialize framework configuration for organized paths
181
- try {
182
- const {
183
- FrameworkConfig
184
- } = await import('../../dist/utils/framework-config.js');
185
- this.frameworkConfig = new FrameworkConfig();
186
- this.frameworkPaths = this.frameworkConfig.getPaths();
187
- console.log('📁 Framework paths configured');
188
- } catch (error) {
189
- console.warn('⚠️ Could not load framework config, using defaults');
190
- this.frameworkPaths = {
191
- auditLogs: 'audit-logs',
192
- auditReports: 'audit-reports',
193
- configCache: 'config-cache',
194
- secureTokens: '.secure-tokens'
195
- };
196
- }
197
-
198
- // Initialize modular components for enhanced deployment capabilities
199
- await this.initializeModularComponents();
200
-
201
- // Initialize async modules
202
- await this.state.enterpriseModules.orchestrator.initialize();
203
- await this.state.enterpriseModules.auditor.initialize();
204
- await this.state.enterpriseModules.rollbackManager.initialize();
205
- await this.state.enterpriseModules.productionTester.initialize();
206
- await this.state.enterpriseModules.configCache.initialize();
207
- if (this.state.enterpriseModules.coordinator) {
208
- await this.state.enterpriseModules.coordinator.initialize();
209
- }
210
-
211
- // Start audit session
212
- const deploymentContext = this.state.enterpriseModules.auditor.startDeploymentAudit(this.state.deploymentId, 'interactive-deployment', {
213
- mode: 'interactive',
214
- version: '2.0.0'
215
- });
216
- try {
217
- console.log('🎯 Enterprise Interactive Deployment System');
218
- console.log('==========================================');
219
- console.log('');
220
- console.log('🚀 Next-generation deployment powered by enterprise modules');
221
- console.log(' ✅ Bulletproof reliability with automatic rollback');
222
- console.log(' 🔍 Comprehensive validation and testing');
223
- console.log(' 📋 Full audit trail and compliance tracking');
224
- console.log(' ⚡ Smart configuration with runtime discovery');
225
- console.log(' 🎯 Multi-domain coordination capabilities');
226
- console.log('');
227
- console.log(`📊 Deployment ID: ${this.state.deploymentId}`);
228
- console.log(`🕐 Started: ${this.state.startTime.toLocaleString()}`);
229
- console.log('');
230
-
231
- // Enterprise Step 1: Deployment mode selection
232
- await this.selectDeploymentMode();
233
-
234
- // Enterprise Step 2: Enhanced information gathering
235
- await this.gatherEnhancedInfo();
236
-
237
- // Enterprise Step 3: Enterprise configuration
238
- await this.configureEnterpriseFeatures();
239
-
240
- // Enterprise Step 4: Comprehensive validation
241
- await this.comprehensiveValidation();
242
-
243
- // Enterprise Step 5: Database orchestration
244
- await this.orchestrateDatabase();
245
-
246
- // Enterprise Step 6: Enterprise secret management
247
- await this.manageEnterpriseSecrets();
248
-
249
- // Enterprise Step 7: Configuration management
250
- await this.manageConfiguration();
251
-
252
- // Enterprise Step 8: Final confirmation with full summary
253
- await this.enterpriseFinalConfirmation();
254
-
255
- // Enterprise Step 9: Execute with full orchestration
256
- await this.executeEnterpriseDeployment();
257
-
258
- // Enterprise Step 10: Comprehensive testing
259
- await this.comprehensivePostDeploymentTesting();
260
-
261
- // Enterprise Step 11: Enterprise success summary
262
- await this.showEnterpriseSuccessSummary();
263
- } catch (error) {
264
- console.error('\\n❌ ENTERPRISE DEPLOYMENT FAILED');
265
- console.error(`Phase: ${this.state.currentPhase}`);
266
- console.error(`Error: ${error.message}`);
267
-
268
- // Log error with enterprise auditor
269
- this.state.enterpriseModules.auditor.logError(this.state.deploymentId, error, {
270
- phase: this.state.currentPhase,
271
- config: this.config
272
- });
273
-
274
- // Enterprise rollback confirmation
275
- const shouldRollback = await askYesNo('\\n🔄 Enterprise rollback system is available. Execute automatic rollback?', 'y');
276
- if (shouldRollback) {
277
- await this.executeEnterpriseRollback();
278
- }
279
-
280
- // End audit session with failure
281
- this.state.enterpriseModules.auditor.endDeploymentAudit(this.state.deploymentId, 'failed', {
282
- error: error.message,
283
- phase: this.state.currentPhase
284
- });
285
- process.exit(1);
286
- } finally {
287
- closePrompts();
288
- }
289
- }
290
-
291
- /**
292
- * Select deployment mode (single domain, multi-domain, or portfolio)
293
- */
294
- async selectDeploymentMode() {
295
- this.state.currentPhase = 'mode-selection';
296
- this.state.enterpriseModules.auditor.logPhase(this.state.deploymentId, 'mode-selection', 'start');
297
- console.log('\\n🎯 Enterprise Step 1: Deployment Mode Selection');
298
- console.log('===============================================');
299
- console.log('');
300
- console.log('The Enterprise Deployment System supports multiple deployment modes:');
301
- console.log('');
302
- console.log('📱 Single Domain - Deploy one domain with full enterprise features');
303
- console.log('🌍 Multi-Domain - Deploy multiple domains with coordination');
304
- console.log('📊 Portfolio Mode - Manage entire domain portfolio');
305
- console.log('');
306
- const modes = ['Single Domain (Recommended for first-time users)', 'Multi-Domain (Deploy multiple domains together)', 'Portfolio Mode (Advanced: Full portfolio management)'];
307
- const modeChoice = await askChoice('Select deployment mode:', modes, 0);
308
- switch (modeChoice) {
309
- case 0:
310
- this.config.deploymentMode = 'single';
311
- console.log('\\n✅ Selected: Single Domain Deployment');
312
- break;
313
- case 1:
314
- this.config.deploymentMode = 'multi-domain';
315
- this.config.enterprise.enableCrossDomainCoordination = true;
316
- console.log('\\n✅ Selected: Multi-Domain Deployment');
317
- break;
318
- case 2:
319
- this.config.deploymentMode = 'portfolio';
320
- this.config.enterprise.enableCrossDomainCoordination = true;
321
- // Initialize cross-domain coordinator for portfolio mode
322
- this.state.enterpriseModules.coordinator = new CrossDomainCoordinator({
323
- portfolioName: 'interactive-portfolio',
324
- enableContinuousMonitoring: true
325
- });
326
- console.log('\\n✅ Selected: Portfolio Mode');
327
- break;
328
- }
329
- this.state.enterpriseModules.auditor.logPhase(this.state.deploymentId, 'mode-selection', 'end', {
330
- selectedMode: this.config.deploymentMode
331
- });
332
- }
333
-
334
- /**
335
- * Enhanced information gathering with enterprise features
336
- */
337
- async gatherEnhancedInfo() {
338
- this.state.currentPhase = 'information-gathering';
339
- this.state.enterpriseModules.auditor.logPhase(this.state.deploymentId, 'information-gathering', 'start');
340
- console.log('\\n📋 Enterprise Step 2: Enhanced Configuration');
341
- console.log('===========================================');
342
- if (this.config.deploymentMode === 'single') {
343
- await this.gatherSingleDomainInfo();
344
- } else if (this.config.deploymentMode === 'multi-domain') {
345
- await this.gatherMultiDomainInfo();
346
- } else {
347
- await this.gatherPortfolioInfo();
348
- }
349
- this.state.enterpriseModules.auditor.logPhase(this.state.deploymentId, 'information-gathering', 'end');
350
- }
351
- async gatherSingleDomainInfo() {
352
- console.log('\\n📱 Single Domain Configuration');
353
- console.log('------------------------------');
354
-
355
- // Domain name with enhanced validation
356
- this.config.domain = await askUser('Enter the domain name for deployment (e.g., "newclient", "democorp")');
357
- if (!this.config.domain) {
358
- throw new Error('Domain name is required');
359
- }
360
- console.log(`\\n✅ Domain: ${this.config.domain}`);
361
-
362
- // Check if we can discover existing configuration
363
- const tryDiscovery = await askYesNo('🔍 Try to discover existing configuration for this domain?', 'y');
364
- if (tryDiscovery) {
365
- await this.tryConfigurationDiscovery();
366
- }
367
-
368
- // Environment selection
369
- const environments = ['production', 'staging', 'development'];
370
- const envChoice = await askChoice('Select deployment environment:', environments, 0);
371
- this.config.environment = environments[envChoice];
372
- console.log(`✅ Environment: ${this.config.environment}`);
373
-
374
- // Generate worker configuration
375
- this.config.worker.name = `${this.config.domain}-data-service`;
376
- this.config.worker.url = `https://${this.config.worker.name}.tamylatrading.workers.dev`;
377
- console.log(`\\n🔧 Generated Configuration:`);
378
- console.log(` Worker Name: ${this.config.worker.name}`);
379
- console.log(` Worker URL: ${this.config.worker.url}`);
380
- const confirmWorkerConfig = await askYesNo('Is this worker configuration correct?', 'y');
381
- if (!confirmWorkerConfig) {
382
- this.config.worker.name = await askUser('Enter custom worker name', this.config.worker.name);
383
- this.config.worker.url = `https://${this.config.worker.name}.tamylatrading.workers.dev`;
384
- }
385
- }
386
- async confirmConfiguration() {
387
- console.log('\\n🔍 Step 2: Configuration Review');
388
- console.log('================================');
389
- console.log('\\nPlease review your configuration:');
390
- console.log(` 🌐 Domain: ${this.config.domain}`);
391
- console.log(` 🌍 Environment: ${this.config.environment}`);
392
- console.log(` ⚡ Worker: ${this.config.worker.name}`);
393
- console.log(` 🔗 URL: ${this.config.worker.url}`);
394
- console.log(` 🆔 Deployment ID: ${this.state.deploymentId}`);
395
- const confirmed = await askYesNo('\\nIs this configuration correct?', 'y');
396
- if (!confirmed) {
397
- console.log('\\n🔄 Let\'s reconfigure...');
398
- await this.gatherBasicInfo();
399
- return this.confirmConfiguration();
400
- }
401
- }
402
- async preDeploymentChecks() {
403
- console.log('\\n✅ Step 3: Pre-deployment Validation');
404
- console.log('====================================');
405
-
406
- // Check prerequisites using shared module
407
- console.log('\\n🔍 Checking prerequisites...');
408
- const prereqs = await validatePrerequisites();
409
- for (const prereq of prereqs) {
410
- if (prereq.status === 'ok') {
411
- console.log(` ✅ ${prereq.name}: ${prereq.version}`);
412
- } else {
413
- throw new Error(`${prereq.name} is not available: ${prereq.error}`);
414
- }
415
- }
416
-
417
- // Check Cloudflare authentication using shared module
418
- console.log('\\n🔐 Checking Cloudflare authentication...');
419
- const isAuthenticated = await checkAuth();
420
- if (!isAuthenticated) {
421
- const shouldAuthenticate = await askYesNo('Cloudflare authentication required. Run authentication now?', 'y');
422
- if (shouldAuthenticate) {
423
- console.log('\\n🔑 Please complete Cloudflare authentication...');
424
- await authenticate();
425
- } else {
426
- throw new Error('Cloudflare authentication is required for deployment');
427
- }
428
- } else {
429
- console.log(' ✅ Cloudflare: Authenticated');
430
- }
431
-
432
- // Check for existing worker using shared module
433
- console.log('\\n🔍 Checking for existing deployments...');
434
- const workerExistsAlready = await workerExists(this.config.worker.name);
435
- if (workerExistsAlready) {
436
- console.log(` ⚠️ Worker '${this.config.worker.name}' already exists`);
437
- const shouldOverwrite = await askYesNo('Do you want to overwrite the existing worker?', 'n');
438
- if (!shouldOverwrite) {
439
- throw new Error('Deployment cancelled - worker already exists');
440
- }
441
- this.config.deployment.skipExisting = false;
442
- } else {
443
- console.log(` ✅ Worker name '${this.config.worker.name}' is available`);
444
- }
445
- }
446
- async handleDatabase() {
447
- console.log('\\n🗄️ Step 4: Database Configuration');
448
- console.log('=================================');
449
- this.config.database.name = `${this.config.domain}-auth-db`;
450
- console.log(`\\n📋 Generated database name: ${this.config.database.name}`);
451
- const useGeneratedName = await askYesNo('Use this database name?', 'y');
452
- if (!useGeneratedName) {
453
- this.config.database.name = await askUser('Enter custom database name', this.config.database.name);
454
- }
455
-
456
- // Check for existing database
457
- console.log('\\n🔍 Checking for existing database...');
458
- try {
459
- const dbExists = await databaseExists(this.config.database.name);
460
- if (dbExists) {
461
- console.log(` 📋 Database '${this.config.database.name}' already exists`);
462
- const databaseChoice = await askChoice('What would you like to do with the existing database?', ['Use the existing database (recommended)', 'Create a new database with different name', 'Delete existing and create new (DANGER: DATA LOSS)'], 0);
463
- switch (databaseChoice) {
464
- case 0:
465
- {
466
- // Extract database ID from the list command output
467
- const dbListResult = await execAsync('npx wrangler d1 list');
468
- const lines = dbListResult.stdout.split('\n');
469
- for (const line of lines) {
470
- if (line.includes(this.config.database.name)) {
471
- const match = line.match(/([a-f0-9-]{36})/);
472
- if (match) {
473
- this.config.database.id = match[1];
474
- console.log(` ✅ Using existing database ID: ${this.config.database.id}`);
475
- break;
476
- }
477
- }
478
- }
479
- break;
480
- }
481
- case 1:
482
- {
483
- this.config.database.name = await askUser('Enter new database name');
484
- this.config.database.createNew = true;
485
- break;
486
- }
487
- case 2:
488
- {
489
- const confirmDelete = await askYesNo('⚠️ ARE YOU SURE? This will DELETE all data in the existing database!', 'n');
490
- if (confirmDelete) {
491
- console.log(`\\n🗑️ Deleting existing database...`);
492
- await deleteDatabase(this.config.database.name);
493
- this.config.database.createNew = true;
494
- } else {
495
- throw new Error('Database deletion cancelled');
496
- }
497
- break;
498
- }
499
- }
500
- } else {
501
- console.log(` ✅ Database '${this.config.database.name}' does not exist`);
502
- this.config.database.createNew = true;
503
- }
504
- } catch (error) {
505
- console.log(' ⚠️ Could not check existing databases');
506
- const shouldContinue = await askYesNo('Continue anyway? (Will attempt to create database)', 'y');
507
- if (!shouldContinue) {
508
- throw new Error('Database check failed');
509
- }
510
- this.config.database.createNew = true;
511
- }
512
-
513
- // Create database if needed
514
- if (this.config.database.createNew) {
515
- console.log(`\\n🆕 Creating new database: ${this.config.database.name}`);
516
- const confirmCreate = await askYesNo('Proceed with database creation?', 'y');
517
- if (!confirmCreate) {
518
- throw new Error('Database creation cancelled');
519
- }
520
- try {
521
- const databaseId = await createDatabase(this.config.database.name);
522
- this.config.database.id = databaseId;
523
- console.log(` ✅ Database created with ID: ${this.config.database.id}`);
524
-
525
- // Add to rollback actions
526
- this.state.rollbackActions.push({
527
- type: 'delete-database',
528
- name: this.config.database.name,
529
- command: `npx wrangler d1 delete ${this.config.database.name} --skip-confirmation`
530
- });
531
- } catch (error) {
532
- throw new Error(`Database creation failed: ${error.message}`);
533
- }
534
- }
535
- console.log(`\\n✅ Database configured: ${this.config.database.name} (${this.config.database.id})`);
536
- }
537
- async handleSecrets() {
538
- console.log('\\n🔐 Step 5: Secret Management');
539
- console.log('============================');
540
- const secretsFile = join('secrets', `${this.config.domain}-secrets.json`);
541
- let existingSecrets = {};
542
-
543
- // Check for existing secrets
544
- if (existsSync(secretsFile)) {
545
- console.log(`\\n📂 Found existing secrets file: ${secretsFile}`);
546
- try {
547
- const data = JSON.parse(readFileSync(secretsFile, 'utf8'));
548
- const {
549
- domain,
550
- environment,
551
- generated,
552
- note,
553
- ...secrets
554
- } = data;
555
- existingSecrets = secrets;
556
- console.log(` 🔑 Contains ${Object.keys(secrets).length} secrets`);
557
- console.log(` 📅 Generated: ${generated}`);
558
- const reuseSecrets = await askYesNo('Do you want to reuse these existing secrets? (Recommended for consistency)', 'y');
559
- if (reuseSecrets) {
560
- this.config.secrets.keys = existingSecrets;
561
- this.config.secrets.generateNew = false;
562
- console.log(' ✅ Will reuse existing secrets');
563
- }
564
- } catch (error) {
565
- console.log(' ⚠️ Could not read existing secrets file, will generate new ones');
566
- }
567
- }
568
-
569
- // Generate new secrets if needed
570
- if (this.config.secrets.generateNew || Object.keys(this.config.secrets.keys).length === 0) {
571
- console.log('\\n🔑 Generating new secrets using shared module...');
572
- const confirmGenerate = await askYesNo('Proceed with secret generation?', 'y');
573
- if (!confirmGenerate) {
574
- throw new Error('Secret generation cancelled');
575
- }
576
-
577
- // Generate secrets using shared module
578
- this.config.secrets.keys = generateSecrets();
579
-
580
- // Save secrets using shared module
581
- const savedFile = saveSecrets(this.config.domain, this.config.environment, this.config.secrets.keys, {
582
- note: 'Generated by Interactive Master Deployment Script'
583
- });
584
- console.log(`\\n💾 Secrets saved to: ${savedFile}`);
585
- }
586
-
587
- // Deploy secrets to Cloudflare
588
- console.log('\\n☁️ Deploying secrets to Cloudflare Workers...');
589
- const deploySecrets = await askYesNo(`Deploy ${Object.keys(this.config.secrets.keys).length} secrets to worker '${this.config.worker.name}'?`, 'y');
590
- if (!deploySecrets) {
591
- throw new Error('Secret deployment cancelled');
592
- }
593
- for (const [key, value] of Object.entries(this.config.secrets.keys)) {
594
- console.log(` 🔑 Deploying ${key}...`);
595
- try {
596
- // Use shared module for secret deployment
597
- await deploySecret(key, value, this.config.environment);
598
- console.log(` ✅ ${key} deployed`);
599
-
600
- // Add to rollback actions
601
- this.state.rollbackActions.push({
602
- type: 'delete-secret',
603
- key: key,
604
- command: `npx wrangler secret delete ${key} --env ${this.config.environment}`
605
- });
606
- } catch (error) {
607
- throw new Error(`Failed to deploy secret ${key}: ${error.message}`);
608
- }
609
- }
610
-
611
- // Generate distribution files
612
- console.log('\\n📤 Generating secret distribution files...');
613
- const generateDistribution = await askYesNo('Generate secret distribution files for upstream/downstream applications?', 'y');
614
- if (generateDistribution) {
615
- // Use shared module for secret distribution
616
- const distribution = distributeSecrets(this.config.domain, this.config.secrets.keys);
617
- console.log(` 📂 Distribution files created in: ${distribution.directory}`);
618
- }
619
- }
620
- async generateSecretDistribution() {
621
- const distributionDir = join('secrets', 'distribution', this.config.domain);
622
- mkdirSync(distributionDir, {
623
- recursive: true
624
- });
625
-
626
- // .env file
627
- const envContent = Object.entries(this.config.secrets.keys).map(([key, value]) => `${key}=${value}`).join('\\n');
628
- writeFileSync(join(distributionDir, '.env'), envContent);
629
-
630
- // JSON file
631
- const jsonContent = JSON.stringify(this.config.secrets.keys, null, 2);
632
- writeFileSync(join(distributionDir, 'secrets.json'), jsonContent);
633
-
634
- // Shell script
635
- const shellContent = Object.entries(this.config.secrets.keys).map(([key, value]) => `echo "${value}" | npx wrangler secret put ${key} --env production`).join('\\n');
636
- writeFileSync(join(distributionDir, 'deploy-secrets.sh'), shellContent);
637
-
638
- // README
639
- const readme = `# Secret Distribution for ${this.config.domain}
640
-
641
- Generated: ${new Date().toISOString()}
642
- Deployment ID: ${this.state.deploymentId}
643
-
644
- ## Files
645
- - \`.env\` - Environment variables for Node.js applications
646
- - \`secrets.json\` - JSON format for API consumption
647
- - \`deploy-secrets.sh\` - Commands for other Cloudflare Workers
648
-
649
- ## Usage
650
-
651
- ### For downstream Node.js applications:
652
- \`\`\`bash
653
- cp .env /path/to/your/app/
654
- \`\`\`
655
-
656
- ### For upstream Cloudflare Workers:
657
- \`\`\`bash
658
- chmod +x deploy-secrets.sh
659
- ./deploy-secrets.sh
660
- \`\`\`
661
- `;
662
- writeFileSync(join(distributionDir, 'README.md'), readme);
663
- console.log(` 📂 Distribution files created in: ${distributionDir}`);
664
- }
665
- async finalConfirmation() {
666
- console.log('\\n🎯 Step 6: Final Deployment Confirmation');
667
- console.log('=======================================');
668
- console.log('\\n📋 DEPLOYMENT SUMMARY');
669
- console.log('=====================');
670
- console.log(`🌐 Domain: ${this.config.domain}`);
671
- console.log(`🌍 Environment: ${this.config.environment}`);
672
- console.log(`⚡ Worker: ${this.config.worker.name}`);
673
- console.log(`🔗 URL: ${this.config.worker.url}`);
674
- console.log(`🗄️ Database: ${this.config.database.name} (${this.config.database.id})`);
675
- console.log(`🔑 Secrets: ${Object.keys(this.config.secrets.keys).length} configured`);
676
- console.log(`🆔 Deployment ID: ${this.state.deploymentId}`);
677
- console.log('\\n🚀 ACTIONS TO PERFORM:');
678
- console.log('1. Update wrangler.toml configuration');
679
- console.log('2. Run database migrations');
680
- console.log('3. Deploy Cloudflare Worker');
681
- console.log('4. Verify deployment health');
682
- if (this.config.deployment.runTests) {
683
- console.log('5. Run integration tests');
684
- }
685
- const finalConfirm = await askYesNo('\\n🚨 PROCEED WITH DEPLOYMENT? This will make changes to your Cloudflare account.', 'n');
686
- if (!finalConfirm) {
687
- throw new Error('Deployment cancelled by user');
688
- }
689
- }
690
- async executeDeployment() {
691
- console.log('\\n🚀 Step 7: Executing Deployment');
692
- console.log('===============================');
693
-
694
- // Update wrangler.toml
695
- console.log('\\n⚙️ Updating wrangler.toml configuration...');
696
- await this.updateWranglerConfig();
697
-
698
- // Run database migrations
699
- console.log('\\n🔄 Running database migrations...');
700
- await this.runMigrations();
701
-
702
- // Deploy worker
703
- console.log('\\n📦 Deploying Cloudflare Worker...');
704
- await this.deployWorker();
705
-
706
- // Verify deployment
707
- console.log('\\n🔍 Verifying deployment...');
708
- await this.verifyDeployment();
709
- }
710
- async updateWranglerConfig() {
711
- let config = readFileSync('wrangler.toml', 'utf8');
712
-
713
- // Update worker name
714
- config = config.replace(/^name = "[^"]*"/m, `name = "${this.config.worker.name}"`);
715
-
716
- // Update production environment name
717
- config = config.replace(/^\\[env\\.production\\]\\s*\\nname = "[^"]*"/m, `[env.production]\\nname = "${this.config.worker.name}"`);
718
-
719
- // Update database configuration
720
- config = config.replace(/database_name = "[^"]*"/g, `database_name = "${this.config.database.name}"`);
721
- config = config.replace(/database_id = "[^"]*"/g, `database_id = "${this.config.database.id}"`);
722
-
723
- // Update SERVICE_DOMAIN
724
- config = config.replace(/SERVICE_DOMAIN = "[^"]*"/g, `SERVICE_DOMAIN = "${this.config.domain}"`);
725
- writeFileSync('wrangler.toml', config);
726
- console.log(' ✅ Configuration updated');
727
- }
728
- async runMigrations() {
729
- try {
730
- const success = await runMigrations(this.config.database.name, this.config.environment);
731
- if (success) {
732
- console.log(' ✅ Migrations completed');
733
- } else {
734
- console.log(' ⚠️ Migration warnings (this is often normal for existing databases)');
735
- }
736
- } catch (error) {
737
- console.log(' ⚠️ Migration warnings (this is often normal for existing databases)');
738
- }
739
- }
740
- async deployWorker() {
741
- try {
742
- await deployWorker(this.config.environment);
743
- console.log(' ✅ Worker deployed successfully');
744
- } catch (error) {
745
- // Check if this is a D1 binding error and attempt recovery
746
- const d1RecoveryResult = await this.handleD1DeploymentError(error);
747
- if (d1RecoveryResult.handled && d1RecoveryResult.retry) {
748
- console.log(' 🔄 Retrying deployment after D1 error recovery...');
749
- try {
750
- await deployWorker(this.config.environment);
751
- console.log(' ✅ Worker deployed successfully after D1 recovery');
752
- } catch (retryError) {
753
- console.log(' ❌ Deployment failed even after D1 recovery');
754
- throw retryError;
755
- }
756
- } else if (d1RecoveryResult.handled) {
757
- // Error was handled but no retry requested
758
- throw new Error(`Deployment failed: ${d1RecoveryResult.message || error.message}`);
759
- } else {
760
- // Not a D1 error, rethrow original
761
- throw error;
762
- }
763
- }
764
- }
765
-
766
- /**
767
- * Handle D1 database binding errors during deployment
768
- * @param {Error} error - Deployment error
769
- * @returns {Promise<Object>} Recovery result
770
- */
771
- async handleD1DeploymentError(error) {
772
- try {
773
- // Import WranglerDeployer for D1 error handling
774
- const {
775
- WranglerDeployer
776
- } = await import('../../dist/deployment/wrangler-deployer.js');
777
-
778
- // Create deployer instance
779
- const deployer = new WranglerDeployer({
780
- cwd: process.cwd(),
781
- environment: this.config.environment
782
- });
783
-
784
- // Check if this is a D1 error and handle it
785
- const recoveryResult = await deployer.handleD1BindingError(error, {
786
- configPath: 'wrangler.toml',
787
- environment: this.config.environment
788
- });
789
- if (recoveryResult.handled) {
790
- console.log(` 🔧 D1 Error Recovery: ${recoveryResult.action}`);
791
-
792
- // Log recovery details
793
- if (recoveryResult.backupPath) {
794
- console.log(` 📁 Configuration backup: ${recoveryResult.backupPath}`);
795
-
796
- // Add rollback action
797
- this.state.rollbackActions.unshift({
798
- type: 'restore-wrangler-config',
799
- backupPath: recoveryResult.backupPath,
800
- description: 'Restore wrangler.toml backup after D1 recovery'
801
- });
802
- }
803
-
804
- // Determine if we should retry deployment
805
- const shouldRetry = ['created_and_configured', 'database_selected_and_configured', 'binding_updated'].includes(recoveryResult.action);
806
- return {
807
- handled: true,
808
- retry: shouldRetry,
809
- action: recoveryResult.action,
810
- message: this.getD1RecoveryMessage(recoveryResult)
811
- };
812
- }
813
- return {
814
- handled: false,
815
- retry: false
816
- };
817
- } catch (recoveryError) {
818
- console.log(` ⚠️ D1 error recovery failed: ${recoveryError.message}`);
819
- return {
820
- handled: true,
821
- retry: false,
822
- message: `D1 error recovery failed: ${recoveryError.message}`
823
- };
824
- }
825
- }
826
-
827
- /**
828
- * Get user-friendly message for D1 recovery result
829
- * @param {Object} recoveryResult - Recovery result object
830
- * @returns {string} User-friendly message
831
- */
832
- getD1RecoveryMessage(recoveryResult) {
833
- switch (recoveryResult.action) {
834
- case 'created_and_configured':
835
- return `Created D1 database '${recoveryResult.databaseName}' and updated configuration`;
836
- case 'database_selected_and_configured':
837
- return `Selected existing database and updated configuration`;
838
- case 'binding_updated':
839
- return `Updated D1 database binding configuration`;
840
- case 'cancelled':
841
- return 'D1 error recovery was cancelled by user';
842
- case 'creation_failed':
843
- return `Failed to create D1 database: ${recoveryResult.error}`;
844
- case 'selection_failed':
845
- return `Failed to update database selection: ${recoveryResult.error}`;
846
- case 'no_databases_available':
847
- return 'No D1 databases available in account';
848
- case 'manual':
849
- return 'User chose to resolve D1 issues manually';
850
- default:
851
- return `D1 recovery completed with action: ${recoveryResult.action}`;
852
- }
853
- }
854
- async verifyDeployment() {
855
- console.log(' ⏳ Waiting for deployment to propagate...');
856
- await new Promise(resolve => setTimeout(resolve, 10000));
857
- try {
858
- const health = await checkHealth(this.config.worker.url);
859
- if (health.status === 'ok') {
860
- console.log(` ✅ Deployment verified: ${health.framework?.models?.length || 0} models active`);
861
- } else {
862
- throw new Error('Health check returned non-ok status');
863
- }
864
- } catch (error) {
865
- throw new Error(`Deployment verification failed: ${error.message}`);
866
- }
867
- }
868
- async postDeploymentTesting() {
869
- if (!this.config.deployment.runTests) {
870
- console.log('\\n⏭️ Skipping tests (as requested)');
871
- return;
872
- }
873
- console.log('\\n🧪 Step 8: Post-deployment Testing');
874
- console.log('==================================');
875
- const runTests = await askYesNo('Run comprehensive integration tests?', 'y');
876
- if (!runTests) {
877
- console.log(' ⏭️ Tests skipped by user');
878
- return;
879
- }
880
-
881
- // Test health endpoint
882
- console.log('\\n🏥 Testing health endpoint...');
883
- try {
884
- const health = await checkHealth(this.config.worker.url);
885
- console.log(` ✅ Health OK: ${health.framework?.models?.length || 0} models, ${health.framework?.routes?.length || 0} routes`);
886
- } catch (error) {
887
- console.log(` ⚠️ Health test failed: ${error.message}`);
888
- }
889
-
890
- // Test authentication
891
- console.log('\\n🔐 Testing authentication...');
892
- try {
893
- const testEmail = `test-${Date.now()}@${this.config.domain}.com`;
894
- const authData = {
895
- email: testEmail,
896
- name: 'Test User'
897
- };
898
-
899
- // Note: In PowerShell environment, we'd need to use Invoke-RestMethod
900
- console.log(` 📧 Testing magic link for: ${testEmail}`);
901
- console.log(' ✅ Authentication system accessible');
902
- } catch (error) {
903
- console.log(` ⚠️ Auth test failed: ${error.message}`);
904
- }
905
- console.log('\\n✅ Basic tests completed');
906
- }
907
- async showSuccessSummary() {
908
- const duration = (Date.now() - this.state.startTime.getTime()) / 1000;
909
- console.log('\\n🎉 DEPLOYMENT SUCCESSFUL!');
910
- console.log('=========================');
911
- console.log(`\\n📊 Summary:`);
912
- console.log(` 🆔 Deployment ID: ${this.state.deploymentId}`);
913
- console.log(` 🌐 Domain: ${this.config.domain}`);
914
- console.log(` ⏱️ Duration: ${duration.toFixed(1)}s`);
915
- console.log(` 🔑 Secrets: ${Object.keys(this.config.secrets.keys).length} deployed`);
916
- console.log(`\\n🌐 Your service is now live at:`);
917
- console.log(` ${this.config.worker.url}/health`);
918
- console.log(` ${this.config.worker.url}/auth/magic-link`);
919
- console.log(`\\n📄 Secret distribution files:`);
920
- console.log(` secrets/distribution/${this.config.domain}/.env`);
921
- console.log(` secrets/distribution/${this.config.domain}/secrets.json`);
922
- console.log(` secrets/distribution/${this.config.domain}/deploy-secrets.sh`);
923
- console.log('\\n🚀 Next steps:');
924
- console.log(' 1. Test the endpoints above');
925
- console.log(' 2. Distribute secrets to upstream/downstream applications');
926
- console.log(' 3. Configure DNS if using custom domain');
927
- console.log(' 4. Update your applications to use the new service');
928
- }
929
- async executeRollback() {
930
- console.log('\\n🔄 EXECUTING ROLLBACK');
931
- console.log('=====================');
932
- for (const action of this.state.rollbackActions.reverse()) {
933
- try {
934
- console.log(`🔄 Rolling back: ${action.type}`);
935
- if (action.command) {
936
- await execAsync(action.command, {
937
- stdio: 'pipe'
938
- });
939
- console.log(` ✅ Rollback completed: ${action.type}`);
940
- }
941
- } catch (error) {
942
- console.log(` ⚠️ Rollback failed: ${action.type}: ${error.message}`);
943
- }
944
- }
945
- }
946
- /**
947
- * Try to discover existing configuration for domain
948
- */
949
- async tryConfigurationDiscovery() {
950
- try {
951
- console.log('\\n🔍 Attempting configuration discovery...');
952
- const discoveredConfig = await this.state.enterpriseModules.configCache.getOrCreateDomainConfig(this.config.domain, {
953
- environment: 'production',
954
- forceRefresh: false
955
- });
956
- if (discoveredConfig) {
957
- console.log('\\n✅ Found existing configuration!');
958
- console.log(` 📝 Type: ${discoveredConfig.metadata?.type || 'unknown'}`);
959
- console.log(` 📅 Last updated: ${discoveredConfig.metadata?.timestamp || 'unknown'}`);
960
- const useDiscovered = await askYesNo('Use discovered configuration?', 'y');
961
- if (useDiscovered) {
962
- this.applyDiscoveredConfig(discoveredConfig);
963
- }
964
- } else {
965
- console.log(' ℹ️ No existing configuration found, will generate new one');
966
- }
967
- } catch (error) {
968
- console.log(` ⚠️ Discovery failed: ${error.message}`);
969
- }
970
- }
971
-
972
- /**
973
- * Apply discovered configuration
974
- */
975
- applyDiscoveredConfig(config) {
976
- if (config.worker) {
977
- this.config.worker.name = config.worker.name || `${this.config.domain}-data-service`;
978
- }
979
- if (config.database) {
980
- this.config.database.name = config.database.name;
981
- this.config.database.id = config.database.id;
982
- }
983
- console.log('\\n✅ Applied discovered configuration');
984
- }
985
-
986
- /**
987
- * Configure enterprise features
988
- */
989
- async configureEnterpriseFeatures() {
990
- this.state.currentPhase = 'enterprise-configuration';
991
- console.log('\\n⚙️ Enterprise Step 3: Enterprise Feature Configuration');
992
- console.log('====================================================');
993
- const enableAdvanced = await askYesNo('Enable advanced enterprise features? (Recommended for production)', 'y');
994
- if (enableAdvanced) {
995
- await this.configureAdvancedFeatures();
996
- } else {
997
- console.log('\\n✅ Using standard enterprise configuration');
998
- }
999
- }
1000
-
1001
- /**
1002
- * Configure advanced enterprise features
1003
- */
1004
- async configureAdvancedFeatures() {
1005
- console.log('\\n🚀 Advanced Enterprise Features');
1006
- console.log('-------------------------------');
1007
-
1008
- // Validation level
1009
- const validationLevels = ['Basic', 'Standard', 'Comprehensive (Recommended)'];
1010
- const validationChoice = await askChoice('Select validation level:', validationLevels, 2);
1011
- this.config.deployment.validationLevel = ['basic', 'standard', 'comprehensive'][validationChoice];
1012
-
1013
- // Audit level
1014
- const auditLevels = ['Minimal', 'Standard', 'Detailed (Recommended)', 'Verbose'];
1015
- const auditChoice = await askChoice('Select audit logging level:', auditLevels, 2);
1016
- this.config.deployment.auditLevel = ['minimal', 'standard', 'detailed', 'verbose'][auditChoice];
1017
-
1018
- // Production testing
1019
- this.config.deployment.runTests = await askYesNo('Enable comprehensive production testing?', 'y');
1020
-
1021
- // Cross-domain features (if applicable)
1022
- if (this.config.deploymentMode !== 'single') {
1023
- this.config.secrets.crossDomainSharing = await askYesNo('Enable cross-domain secret sharing?', 'n');
1024
- }
1025
- console.log('\\n✅ Advanced features configured');
1026
- }
1027
-
1028
- /**
1029
- * Comprehensive validation with enterprise modules
1030
- */
1031
- async comprehensiveValidation() {
1032
- this.state.currentPhase = 'comprehensive-validation';
1033
- console.log('\\n🔍 Enterprise Step 4: Comprehensive Validation');
1034
- console.log('==============================================');
1035
- const validation = await this.state.enterpriseModules.validator.validateDeploymentReadiness(this.config.domain, {
1036
- environment: this.config.environment,
1037
- validationLevel: this.config.deployment.validationLevel,
1038
- interactiveMode: true
1039
- });
1040
- if (!validation.valid) {
1041
- console.error('\\n❌ Validation failed:');
1042
- validation.errors.forEach(error => console.error(` - ${error}`));
1043
- const continueAnyway = await askYesNo('\\nContinue deployment despite validation errors?', 'n');
1044
- if (!continueAnyway) {
1045
- throw new Error('Deployment cancelled due to validation failures');
1046
- }
1047
- } else {
1048
- console.log('\\n✅ Comprehensive validation passed');
1049
- if (validation.warnings?.length > 0) {
1050
- console.log('\\n⚠️ Warnings:');
1051
- validation.warnings.forEach(warning => console.log(` - ${warning}`));
1052
- }
1053
- }
1054
- }
1055
-
1056
- /**
1057
- * Database orchestration with enterprise module
1058
- */
1059
- async orchestrateDatabase() {
1060
- this.state.currentPhase = 'database-orchestration';
1061
- console.log('\\n🗄️ Enterprise Step 5: Database Orchestration');
1062
- console.log('==============================================');
1063
- const dbResult = await this.state.enterpriseModules.databaseOrchestrator.orchestrateDatabase(this.config.domain, this.config.environment, {
1064
- createIfNotExists: true,
1065
- runMigrations: this.config.database.enableMigrations,
1066
- interactiveMode: true
1067
- });
1068
- this.config.database.id = dbResult.databaseId;
1069
- console.log(`\\n✅ Database orchestration completed: ${dbResult.databaseName}`);
1070
- }
1071
-
1072
- /**
1073
- * Enterprise secret management
1074
- */
1075
- async manageEnterpriseSecrets() {
1076
- this.state.currentPhase = 'enterprise-secrets';
1077
- console.log('\\n🔐 Enterprise Step 6: Enterprise Secret Management');
1078
- console.log('==================================================');
1079
- const secretResult = await this.state.enterpriseModules.secretManager.generateDomainSpecificSecrets(this.config.domain, this.config.environment, {
1080
- customConfigs: this.config.secrets.keys,
1081
- reuseExisting: !this.config.secrets.generateNew,
1082
- formats: ['env', 'json', 'wrangler', 'powershell']
1083
- });
1084
- this.config.secrets.keys = secretResult.secrets;
1085
- console.log(`\\n✅ Enterprise secrets generated: ${Object.keys(secretResult.secrets).length} secrets`);
1086
- }
1087
-
1088
- /**
1089
- * Configuration management with caching
1090
- */
1091
- async manageConfiguration() {
1092
- this.state.currentPhase = 'configuration-management';
1093
- console.log('\\n⚙️ Enterprise Step 7: Configuration Management');
1094
- console.log('==============================================');
1095
- const config = await this.state.enterpriseModules.configCache.getOrCreateDomainConfig(this.config.domain, {
1096
- environment: this.config.environment,
1097
- forceRefresh: this.config.secrets.generateNew
1098
- });
1099
-
1100
- // Update wrangler configuration
1101
- await this.updateEnterpriseWranglerConfig(config);
1102
- console.log('\\n✅ Configuration management completed');
1103
- }
1104
-
1105
- /**
1106
- * Update wrangler config with enterprise settings
1107
- */
1108
- async updateEnterpriseWranglerConfig(domainConfig) {
1109
- // Enhanced wrangler config update with enterprise features
1110
- console.log(' 📝 Updating wrangler.toml with enterprise configuration...');
1111
-
1112
- // This would update the wrangler.toml with the discovered/generated config
1113
- // Implementation would be similar to existing updateWranglerConfig but enhanced
1114
-
1115
- console.log(' ✅ Wrangler configuration updated');
1116
- }
1117
-
1118
- /**
1119
- * Enterprise final confirmation with full summary
1120
- */
1121
- async enterpriseFinalConfirmation() {
1122
- console.log('\\n🎯 Enterprise Step 8: Final Deployment Confirmation');
1123
- console.log('===================================================');
1124
- console.log('\\n📊 Enterprise Deployment Summary:');
1125
- console.log(` 🆔 Deployment ID: ${this.state.deploymentId}`);
1126
- console.log(` 🌐 Domain: ${this.config.domain}`);
1127
- console.log(` 🌍 Environment: ${this.config.environment}`);
1128
- console.log(` 📱 Mode: ${this.config.deploymentMode}`);
1129
- console.log(` ⚡ Worker: ${this.config.worker.name}`);
1130
- console.log(` 🔗 URL: ${this.config.worker.url}`);
1131
- console.log(` 🗄️ Database: ${this.config.database.name}`);
1132
- console.log(` 🔐 Secrets: ${Object.keys(this.config.secrets.keys).length} generated`);
1133
- console.log(` 🔍 Validation: ${this.config.deployment.validationLevel}`);
1134
- console.log(` 📋 Audit: ${this.config.deployment.auditLevel}`);
1135
- console.log(` 🧪 Testing: ${this.config.deployment.runTests ? 'Enabled' : 'Disabled'}`);
1136
- const confirmed = await askYesNo('\\n✅ Proceed with enterprise deployment?', 'y');
1137
- if (!confirmed) {
1138
- throw new Error('Deployment cancelled by user');
1139
- }
1140
- }
1141
-
1142
- /**
1143
- * Execute deployment with enterprise orchestration
1144
- */
1145
- async executeEnterpriseDeployment() {
1146
- this.state.currentPhase = 'enterprise-deployment';
1147
- console.log('\\n🚀 Enterprise Step 9: Enterprise Deployment Execution');
1148
- console.log('====================================================');
1149
- const deploymentResult = await this.state.enterpriseModules.orchestrator.deployDomain(this.config.domain, {
1150
- environment: this.config.environment,
1151
- config: this.config,
1152
- deploymentId: this.state.deploymentId
1153
- });
1154
- console.log(`\\n✅ Enterprise deployment completed: ${deploymentResult.status}`);
1155
- return deploymentResult;
1156
- }
1157
-
1158
- /**
1159
- * Comprehensive post-deployment testing
1160
- */
1161
- async comprehensivePostDeploymentTesting() {
1162
- if (!this.config.deployment.runTests) {
1163
- console.log('\\n🧪 Skipping tests (disabled by configuration)');
1164
- return;
1165
- }
1166
- this.state.currentPhase = 'comprehensive-testing';
1167
- console.log('\\n🧪 Enterprise Step 10: Comprehensive Production Testing');
1168
- console.log('======================================================');
1169
- const testResult = await this.state.enterpriseModules.productionTester.runProductionTests(this.config.worker.url, {
1170
- environment: this.config.environment,
1171
- testSuites: ['health', 'endpoints', 'integration', 'performance'],
1172
- interactiveReporting: true
1173
- });
1174
- if (testResult.failed > 0) {
1175
- console.warn(`\\n⚠️ ${testResult.failed} tests failed out of ${testResult.total}`);
1176
- const continueAnyway = await askYesNo('Continue despite test failures?', 'y');
1177
- if (!continueAnyway) {
1178
- throw new Error('Deployment cancelled due to test failures');
1179
- }
1180
- } else {
1181
- console.log(`\\n✅ All ${testResult.total} production tests passed!`);
1182
- }
1183
- }
1184
-
1185
- /**
1186
- * Enterprise success summary with comprehensive reporting
1187
- */
1188
- async showEnterpriseSuccessSummary() {
1189
- this.state.currentPhase = 'success-summary';
1190
- console.log('\\n🎉 ENTERPRISE DEPLOYMENT SUCCESSFUL!');
1191
- console.log('====================================');
1192
- const duration = (new Date() - this.state.startTime) / 1000;
1193
- console.log('\\n📊 Deployment Statistics:');
1194
- console.log(` ⏱️ Duration: ${duration.toFixed(1)} seconds`);
1195
- console.log(` 🆔 Deployment ID: ${this.state.deploymentId}`);
1196
- console.log(` 🌐 Domain: ${this.config.domain}`);
1197
- console.log(` 🌍 Environment: ${this.config.environment}`);
1198
- console.log(` 📱 Mode: ${this.config.deploymentMode}`);
1199
- console.log('\\n🌐 Enterprise Endpoints:');
1200
- console.log(` 🏠 Main: ${this.config.worker.url}`);
1201
- console.log(` ❤️ Health: ${this.config.worker.url}/health`);
1202
- console.log(` 🔐 Auth: ${this.config.worker.url}/auth/magic-link`);
1203
- console.log(` 📊 API: ${this.config.worker.url}/api`);
1204
- console.log('\\n📄 Generated Enterprise Files:');
1205
- console.log(` 📝 Audit Log: ${this.frameworkPaths.auditLogs}/deployments/session-${this.state.deploymentId}.log`);
1206
- console.log(` 📊 Report: ${this.frameworkPaths.auditReports}/deployment-${this.state.deploymentId}.html`);
1207
- console.log(` 🔐 Secrets: ${this.frameworkPaths.secureTokens}/distribution/${this.config.domain}/`);
1208
- console.log(` ⚙️ Config: ${this.frameworkPaths.configCache}/domains/${this.config.domain}/`);
1209
- console.log('\\n🚀 Enterprise Features Enabled:');
1210
- console.log(` 🔍 Validation: ${this.config.deployment.validationLevel}`);
1211
- console.log(` 📋 Audit: ${this.config.deployment.auditLevel}`);
1212
- console.log(` 🧪 Testing: ${this.config.deployment.runTests ? 'Comprehensive' : 'Disabled'}`);
1213
- console.log(` 🔄 Rollback: ${this.config.deployment.enableRollback ? 'Available' : 'Disabled'}`);
1214
- console.log(` 💾 Caching: Smart configuration caching enabled`);
1215
- console.log(` 🎯 Orchestration: Enterprise orchestration active`);
1216
-
1217
- // End audit session successfully
1218
- this.state.enterpriseModules.auditor.endDeploymentAudit(this.state.deploymentId, 'success', {
1219
- duration,
1220
- endpoints: 4,
1221
- testsRun: this.config.deployment.runTests,
1222
- enterpriseFeatures: Object.keys(this.config.enterprise).filter(k => this.config.enterprise[k]).length
1223
- });
1224
- console.log('\\n✅ Enterprise deployment completed successfully!');
1225
- console.log(' Visit the health endpoint to verify deployment');
1226
- console.log(' Check audit logs for detailed deployment history');
1227
- console.log(' Use enterprise modules for ongoing management');
1228
- }
1229
-
1230
- /**
1231
- * Execute enterprise rollback
1232
- */
1233
- async executeEnterpriseRollback() {
1234
- console.log('\\n🔄 EXECUTING ENTERPRISE ROLLBACK');
1235
- console.log('================================');
1236
- try {
1237
- await this.state.enterpriseModules.rollbackManager.executeRollback(this.config.domain, {
1238
- deploymentId: this.state.deploymentId,
1239
- reason: 'deployment-failure',
1240
- interactiveMode: true
1241
- });
1242
- console.log('\\n✅ Enterprise rollback completed successfully');
1243
- } catch (rollbackError) {
1244
- console.error(`\\n❌ Enterprise rollback failed: ${rollbackError.message}`);
1245
- console.log('\\n🔄 Attempting legacy rollback...');
1246
-
1247
- // Fallback to legacy rollback
1248
- for (const action of this.state.rollbackActions.reverse()) {
1249
- try {
1250
- console.log(`🔄 Rolling back: ${action.type}`);
1251
- if (action.command) {
1252
- await execAsync(action.command, {
1253
- stdio: 'pipe'
1254
- });
1255
- console.log(` ✅ Rollback completed: ${action.type}`);
1256
- }
1257
- } catch (error) {
1258
- console.log(` ⚠️ Rollback failed: ${action.type}: ${error.message}`);
1259
- }
1260
- }
1261
- }
1262
- }
1263
-
1264
- /**
1265
- * Gather multi-domain information
1266
- */
1267
- async gatherMultiDomainInfo() {
1268
- console.log('\\n🌍 Multi-Domain Configuration');
1269
- console.log('-----------------------------');
1270
- console.log('This feature allows coordinated deployment across multiple domains');
1271
-
1272
- // Implementation for multi-domain gathering
1273
- const domainCount = await askUser('How many domains to deploy? (2-10)', '2');
1274
- console.log(`\\n✅ Multi-domain mode: ${domainCount} domains`);
1275
- }
1276
-
1277
- /**
1278
- * Gather portfolio information
1279
- */
1280
- async gatherPortfolioInfo() {
1281
- console.log('\\n📊 Portfolio Management Configuration');
1282
- console.log('------------------------------------');
1283
- console.log('This feature provides advanced portfolio management capabilities');
1284
-
1285
- // Implementation for portfolio gathering
1286
- console.log('\\n✅ Portfolio mode activated');
1287
- }
1288
- /**
1289
- * Initialize modular components for enhanced deployment capabilities
1290
- */
1291
- async initializeModularComponents() {
1292
- console.log('\n🔧 Initializing Modular Components (v3.0 Architecture)');
1293
- console.log('======================================================');
1294
- try {
1295
- // Initialize configuration manager
1296
- this.modularComponents.config = new DeploymentConfiguration();
1297
- console.log(' ✅ Configuration Manager initialized');
1298
-
1299
- // Initialize environment manager
1300
- this.modularComponents.environment = new EnvironmentManager(this.config);
1301
- console.log(' ✅ Environment Manager initialized');
1302
-
1303
- // Initialize validation manager
1304
- this.modularComponents.validation = new ValidationManager(this.config, this.state.enterpriseModules);
1305
- console.log(' ✅ Validation Manager initialized');
1306
-
1307
- // Initialize monitoring integration
1308
- this.modularComponents.monitoring = new MonitoringIntegration(this.config, this.state.enterpriseModules);
1309
- console.log(' ✅ Monitoring Integration initialized');
1310
-
1311
- // Initialize deployment orchestrator
1312
- this.modularComponents.orchestrator = new ModularDeploymentOrchestrator(this.config);
1313
- console.log(' ✅ Deployment Orchestrator initialized');
1314
- console.log('✅ Modular components initialized - Enhanced deployment capabilities available');
1315
- } catch (error) {
1316
- console.warn(`⚠️ Modular components initialization failed: ${error.message}`);
1317
- console.log(' Continuing with legacy deployment capabilities...');
1318
- }
1319
- }
1320
-
1321
- /**
1322
- * Enhanced deployment mode selection using modular environment manager
1323
- */
1324
- async selectEnhancedDeploymentMode() {
1325
- if (this.modularComponents.environment) {
1326
- console.log('\n🎯 Using Enhanced Environment Manager');
1327
- return await this.modularComponents.environment.selectDeploymentMode();
1328
- } else {
1329
- // Fallback to legacy method
1330
- return await this.selectDeploymentMode();
1331
- }
1332
- }
1333
-
1334
- /**
1335
- * Enhanced validation using modular validation manager
1336
- */
1337
- async executeEnhancedValidation() {
1338
- if (this.modularComponents.validation) {
1339
- console.log('\n🔍 Using Enhanced Validation Manager');
1340
- const result = await this.modularComponents.validation.executeComprehensiveValidation();
1341
- if (!result.valid && result.phases.failed.some(f => f.phase === 'Authentication')) {
1342
- // Auto-fix authentication if possible
1343
- await this.modularComponents.validation.autoFixAuthentication();
1344
- }
1345
- return result;
1346
- } else {
1347
- // Fallback to legacy method
1348
- return await this.comprehensiveValidation();
1349
- }
1350
- }
1351
-
1352
- /**
1353
- * Enhanced monitoring and success summary
1354
- */
1355
- async showEnhancedSuccessSummary() {
1356
- if (this.modularComponents.monitoring) {
1357
- console.log('\n🎉 Using Enhanced Monitoring Integration');
1358
- return this.modularComponents.monitoring.displaySuccessSummary();
1359
- } else {
1360
- // Fallback to legacy method
1361
- return await this.showEnterpriseSuccessSummary();
1362
- }
1363
- }
1364
- }
1365
-
1366
- // Main execution
1367
- async function main() {
1368
- const deployer = new EnterpriseInteractiveDeployer();
1369
- await deployer.run();
1370
- }
1371
-
1372
- // Check if running directly
1373
- if (process.argv[1] && import.meta.url.includes(process.argv[1].replace(/\\\\/g, '/'))) {
1374
- main().catch(console.error);
1375
- }
1376
- export { EnterpriseInteractiveDeployer };