@tamyla/clodo-framework 3.1.22 → 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 (208) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +230 -1
  3. package/dist/cli/commands/assess.js +183 -0
  4. package/dist/cli/commands/create.js +77 -0
  5. package/dist/{bin → cli}/commands/deploy.js +8 -8
  6. package/dist/cli/commands/diagnose.js +83 -0
  7. package/dist/{bin → cli}/commands/helpers/deployment-verification.js +2 -3
  8. package/dist/{bin → cli}/commands/helpers/error-recovery.js +1 -1
  9. package/dist/{bin → cli}/commands/helpers/resource-detection.js +1 -1
  10. package/dist/cli/commands/helpers.js +110 -0
  11. package/dist/cli/commands/init-config.js +57 -0
  12. package/dist/cli/commands/update.js +75 -0
  13. package/dist/{bin → cli}/commands/validate.js +5 -5
  14. package/dist/cli/security-cli.js +118 -0
  15. package/dist/config/FeatureManager.js +6 -0
  16. package/dist/config/clodo-create.example.json +26 -0
  17. package/dist/config/clodo-deploy.example.json +41 -0
  18. package/dist/config/clodo-update.example.json +46 -0
  19. package/dist/config/clodo-validate.example.json +41 -0
  20. package/dist/config/customers/template/development.env.template +37 -0
  21. package/dist/config/customers/template/production.env.template +39 -0
  22. package/dist/config/customers/template/staging.env.template +37 -0
  23. package/dist/config/customers.js +625 -0
  24. package/dist/config/domain-examples/README.md +464 -0
  25. package/dist/config/domain-examples/environment-mapped.json +168 -0
  26. package/dist/config/domain-examples/multi-domain.json +144 -0
  27. package/dist/config/domain-examples/single-domain.json +50 -0
  28. package/dist/config/domains.js +186 -0
  29. package/dist/config/examples +12 -0
  30. package/dist/config/features.js +61 -0
  31. package/dist/config/index.js +6 -0
  32. package/dist/config/staging-deployment.json +60 -0
  33. package/dist/config/validation-config.json +347 -0
  34. package/dist/database/database-orchestrator.js +795 -0
  35. package/dist/database/index.js +4 -0
  36. package/dist/deployment/index.js +11 -0
  37. package/dist/deployment/orchestration/BaseDeploymentOrchestrator.js +426 -0
  38. package/dist/deployment/orchestration/PortfolioOrchestrator.js +273 -0
  39. package/dist/deployment/orchestration/SingleServiceOrchestrator.js +231 -0
  40. package/dist/deployment/orchestration/UnifiedDeploymentOrchestrator.js +662 -0
  41. package/dist/deployment/orchestration/index.js +17 -0
  42. package/dist/deployment/rollback-manager.js +36 -0
  43. package/dist/deployment/wrangler-deployer.js +640 -0
  44. package/dist/handlers/GenericRouteHandler.js +532 -0
  45. package/dist/lib/database/deployment-db-manager.js +423 -0
  46. package/dist/lib/database/wrangler-d1-manager.js +685 -0
  47. package/dist/lib/deployment/modules/DeploymentConfiguration.js +395 -0
  48. package/dist/lib/deployment/modules/DeploymentOrchestrator.js +492 -0
  49. package/dist/lib/deployment/modules/EnvironmentManager.js +517 -0
  50. package/dist/lib/deployment/modules/MonitoringIntegration.js +560 -0
  51. package/dist/lib/deployment/modules/ValidationManager.js +342 -0
  52. package/dist/lib/deployment/orchestration/BaseDeploymentOrchestrator.js +426 -0
  53. package/dist/lib/deployment/orchestration/EnterpriseOrchestrator.js +21 -0
  54. package/dist/lib/deployment/orchestration/PortfolioOrchestrator.js +273 -0
  55. package/dist/lib/deployment/orchestration/SingleServiceOrchestrator.js +231 -0
  56. package/dist/lib/deployment/orchestration/UnifiedDeploymentOrchestrator.js +662 -0
  57. package/dist/{bin → lib}/shared/cloudflare/domain-discovery.js +1 -1
  58. package/dist/{bin → lib}/shared/cloudflare/domain-manager.js +1 -1
  59. package/dist/{bin → lib}/shared/cloudflare/ops.js +4 -4
  60. package/dist/{bin → lib}/shared/config/command-config-manager.js +1 -1
  61. package/dist/{bin → lib}/shared/config/index.js +1 -1
  62. package/dist/{bin → lib}/shared/deployment/credential-collector.js +1 -1
  63. package/dist/lib/shared/deployment/index.js +10 -0
  64. package/dist/{bin → lib}/shared/deployment/rollback-manager.js +1 -1
  65. package/dist/{bin → lib}/shared/deployment/utilities/d1-error-recovery.js +1 -1
  66. package/dist/{bin → lib}/shared/deployment/validator.js +1 -1
  67. package/dist/{bin → lib}/shared/deployment/workflows/interactive-database-workflow.js +1 -1
  68. package/dist/{bin → lib}/shared/monitoring/health-checker.js +2 -2
  69. package/dist/{bin → lib}/shared/routing/domain-router.js +1 -1
  70. package/dist/{bin → lib}/shared/validation/ValidationRegistry.js +1 -1
  71. package/dist/migration/MigrationAdapters.js +608 -0
  72. package/dist/modules/ModuleManager.js +668 -0
  73. package/dist/modules/security.js +96 -0
  74. package/dist/orchestration/cross-domain-coordinator.js +1083 -0
  75. package/dist/orchestration/index.js +5 -0
  76. package/dist/orchestration/modules/DeploymentCoordinator.js +368 -0
  77. package/dist/orchestration/modules/DomainResolver.js +198 -0
  78. package/dist/orchestration/modules/StateManager.js +332 -0
  79. package/dist/orchestration/multi-domain-orchestrator.js +765 -0
  80. package/dist/routing/EnhancedRouter.js +158 -0
  81. package/dist/schema/SchemaManager.js +778 -0
  82. package/dist/security/index.js +2 -2
  83. package/dist/service-management/ConfirmationEngine.js +412 -0
  84. package/dist/service-management/ErrorTracker.js +299 -0
  85. package/dist/service-management/GenerationEngine.js +447 -0
  86. package/dist/service-management/InputCollector.js +619 -0
  87. package/dist/service-management/ServiceCreator.js +21 -0
  88. package/dist/service-management/ServiceOrchestrator.js +631 -0
  89. package/dist/service-management/generators/BaseGenerator.js +233 -0
  90. package/dist/service-management/generators/GeneratorRegistry.js +254 -0
  91. package/dist/service-management/generators/cicd/CiWorkflowGenerator.js +87 -0
  92. package/dist/service-management/generators/cicd/DeployWorkflowGenerator.js +106 -0
  93. package/dist/service-management/generators/code/ServiceHandlersGenerator.js +235 -0
  94. package/dist/service-management/generators/code/ServiceMiddlewareGenerator.js +116 -0
  95. package/dist/service-management/generators/code/ServiceUtilsGenerator.js +246 -0
  96. package/dist/service-management/generators/code/WorkerIndexGenerator.js +143 -0
  97. package/dist/service-management/generators/config/DevelopmentEnvGenerator.js +101 -0
  98. package/dist/service-management/generators/config/DomainsConfigGenerator.js +175 -0
  99. package/dist/service-management/generators/config/EnvExampleGenerator.js +178 -0
  100. package/dist/service-management/generators/config/ProductionEnvGenerator.js +97 -0
  101. package/dist/service-management/generators/config/StagingEnvGenerator.js +97 -0
  102. package/dist/service-management/generators/config/WranglerTomlGenerator.js +238 -0
  103. package/dist/service-management/generators/core/PackageJsonGenerator.js +243 -0
  104. package/dist/service-management/generators/core/SiteConfigGenerator.js +115 -0
  105. package/dist/service-management/generators/documentation/ApiDocsGenerator.js +331 -0
  106. package/dist/service-management/generators/documentation/ConfigurationDocsGenerator.js +294 -0
  107. package/dist/service-management/generators/documentation/DeploymentDocsGenerator.js +244 -0
  108. package/dist/service-management/generators/documentation/ReadmeGenerator.js +196 -0
  109. package/dist/service-management/generators/schemas/ServiceSchemaGenerator.js +190 -0
  110. package/dist/service-management/generators/scripts/DeployScriptGenerator.js +123 -0
  111. package/dist/service-management/generators/scripts/HealthCheckScriptGenerator.js +101 -0
  112. package/dist/service-management/generators/scripts/SetupScriptGenerator.js +88 -0
  113. package/dist/service-management/generators/service-types/StaticSiteGenerator.js +342 -0
  114. package/dist/service-management/generators/testing/EslintConfigGenerator.js +85 -0
  115. package/dist/service-management/generators/testing/IntegrationTestsGenerator.js +237 -0
  116. package/dist/service-management/generators/testing/JestConfigGenerator.js +72 -0
  117. package/dist/service-management/generators/testing/UnitTestsGenerator.js +277 -0
  118. package/dist/service-management/generators/tooling/DockerComposeGenerator.js +71 -0
  119. package/dist/service-management/generators/tooling/GitignoreGenerator.js +143 -0
  120. package/dist/service-management/generators/utils/FileWriter.js +179 -0
  121. package/dist/service-management/generators/utils/PathResolver.js +157 -0
  122. package/dist/service-management/generators/utils/ServiceManifestGenerator.js +111 -0
  123. package/dist/service-management/generators/utils/TemplateEngine.js +185 -0
  124. package/dist/service-management/generators/utils/index.js +18 -0
  125. package/dist/service-management/handlers/ConfirmationHandler.js +71 -0
  126. package/dist/service-management/handlers/GenerationHandler.js +80 -0
  127. package/dist/service-management/handlers/InputHandler.js +59 -0
  128. package/dist/service-management/handlers/ValidationHandler.js +203 -0
  129. package/dist/service-management/index.js +14 -0
  130. package/dist/service-management/routing/DomainRouteMapper.js +311 -0
  131. package/dist/service-management/routing/RouteGenerator.js +266 -0
  132. package/dist/service-management/routing/WranglerRoutesBuilder.js +273 -0
  133. package/dist/service-management/routing/index.js +14 -0
  134. package/dist/service-management/services/DirectoryStructureService.js +56 -0
  135. package/dist/service-management/services/GenerationCoordinator.js +208 -0
  136. package/dist/service-management/services/GeneratorRegistry.js +174 -0
  137. package/dist/services/GenericDataService.js +501 -0
  138. package/dist/ui-structures/concepts/second-order-acquisition-strategy.md +286 -0
  139. package/dist/ui-structures/concepts/service-lifecycle-management.md +150 -0
  140. package/dist/ui-structures/concepts/service-manifest-guide.md +309 -0
  141. package/dist/ui-structures/concepts/three-tier-categorization-strategy.md +231 -0
  142. package/dist/ui-structures/creation/automated-generation-ui.json +246 -0
  143. package/dist/ui-structures/creation/core-inputs-ui.json +217 -0
  144. package/dist/ui-structures/creation/smart-confirmable-ui.json +451 -0
  145. package/dist/ui-structures/reference/absolutely-required-inputs.json +315 -0
  146. package/dist/ui-structures/reference/service-manifest-template.json +342 -0
  147. package/dist/utils/cloudflare/ops.js +1 -1
  148. package/dist/utils/file-manager.js +1 -1
  149. package/dist/utils/formatters.js +1 -1
  150. package/dist/utils/logger.js +1 -1
  151. package/dist/version/VersionDetector.js +813 -0
  152. package/dist/worker/index.js +4 -0
  153. package/dist/worker/integration.js +351 -0
  154. package/package.json +7 -15
  155. package/dist/bin/security/security-cli.js +0 -108
  156. package/dist/bin/shared/deployment/index.js +0 -10
  157. /package/dist/{bin → cli}/clodo-service.js +0 -0
  158. /package/dist/{bin → cli}/commands/helpers/deployment-ui.js +0 -0
  159. /package/dist/{bin → lib}/shared/cache/configuration-cache.js +0 -0
  160. /package/dist/{bin → lib}/shared/cloudflare/index.js +0 -0
  161. /package/dist/{bin → lib}/shared/config/ConfigurationManager.js +0 -0
  162. /package/dist/{bin → lib}/shared/config/cache.js +0 -0
  163. /package/dist/{bin → lib}/shared/config/cloudflare-service-validator.js +0 -0
  164. /package/dist/{bin → lib}/shared/config/manager.js +0 -0
  165. /package/dist/{bin → lib}/shared/config/manifest-loader.js +0 -0
  166. /package/dist/{bin → lib}/shared/database/connection-manager.js +0 -0
  167. /package/dist/{bin → lib}/shared/database/index.js +0 -0
  168. /package/dist/{bin → lib}/shared/database/orchestrator.js +0 -0
  169. /package/dist/{bin → lib}/shared/deployment/auditor.js +0 -0
  170. /package/dist/{bin → lib}/shared/deployment/workflows/deployment-summary.js +0 -0
  171. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-confirmation.js +0 -0
  172. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-domain-info-gatherer.js +0 -0
  173. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-secret-workflow.js +0 -0
  174. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-testing-workflow.js +0 -0
  175. /package/dist/{bin → lib}/shared/deployment/workflows/interactive-validation.js +0 -0
  176. /package/dist/{bin → lib}/shared/error-handling/error-classifier.js +0 -0
  177. /package/dist/{bin → lib}/shared/index.js +0 -0
  178. /package/dist/{bin → lib}/shared/logging/Logger.js +0 -0
  179. /package/dist/{bin → lib}/shared/monitoring/index.js +0 -0
  180. /package/dist/{bin → lib}/shared/monitoring/memory-manager.js +0 -0
  181. /package/dist/{bin → lib}/shared/monitoring/production-monitor.js +0 -0
  182. /package/dist/{bin → lib}/shared/production-tester/api-tester.js +0 -0
  183. /package/dist/{bin → lib}/shared/production-tester/auth-tester.js +0 -0
  184. /package/dist/{bin → lib}/shared/production-tester/core.js +0 -0
  185. /package/dist/{bin → lib}/shared/production-tester/database-tester.js +0 -0
  186. /package/dist/{bin → lib}/shared/production-tester/index.js +0 -0
  187. /package/dist/{bin → lib}/shared/production-tester/load-tester.js +0 -0
  188. /package/dist/{bin → lib}/shared/production-tester/performance-tester.js +0 -0
  189. /package/dist/{bin → lib}/shared/security/api-token-manager.js +0 -0
  190. /package/dist/{bin → lib}/shared/security/index.js +0 -0
  191. /package/dist/{bin → lib}/shared/security/secret-generator.js +0 -0
  192. /package/dist/{bin → lib}/shared/security/secure-token-manager.js +0 -0
  193. /package/dist/{bin → lib}/shared/utils/ErrorHandler.js +0 -0
  194. /package/dist/{bin → lib}/shared/utils/cli-options.js +0 -0
  195. /package/dist/{bin → lib}/shared/utils/config-loader.js +0 -0
  196. /package/dist/{bin → lib}/shared/utils/deployment-validator.js +0 -0
  197. /package/dist/{bin → lib}/shared/utils/error-recovery.js +0 -0
  198. /package/dist/{bin → lib}/shared/utils/file-manager.js +0 -0
  199. /package/dist/{bin → lib}/shared/utils/formatters.js +0 -0
  200. /package/dist/{bin → lib}/shared/utils/graceful-shutdown-manager.js +0 -0
  201. /package/dist/{bin → lib}/shared/utils/index.js +0 -0
  202. /package/dist/{bin → lib}/shared/utils/interactive-prompts.js +0 -0
  203. /package/dist/{bin → lib}/shared/utils/interactive-utils.js +0 -0
  204. /package/dist/{bin → lib}/shared/utils/output-formatter.js +0 -0
  205. /package/dist/{bin → lib}/shared/utils/progress-manager.js +0 -0
  206. /package/dist/{bin → lib}/shared/utils/progress-spinner.js +0 -0
  207. /package/dist/{bin → lib}/shared/utils/rate-limiter.js +0 -0
  208. /package/dist/{bin → lib}/shared/utils/sensitive-redactor.js +0 -0
@@ -0,0 +1,235 @@
1
+ import { BaseGenerator } from '../BaseGenerator.js';
2
+ import { join } from 'path';
3
+ import { mkdirSync, writeFileSync } from 'fs';
4
+
5
+ /**
6
+ * Service Handlers Generator
7
+ * Generates request handlers with routing, health checks, and API endpoints
8
+ */
9
+ export class ServiceHandlersGenerator extends BaseGenerator {
10
+ /**
11
+ * Generate service handlers
12
+ * @param {Object} context - Generation context
13
+ * @returns {Promise<string>} Path to generated handlers file
14
+ */
15
+ async generate(context) {
16
+ const {
17
+ coreInputs,
18
+ confirmedValues,
19
+ servicePath
20
+ } = this.extractContext(context);
21
+ if (!this.shouldGenerate(context)) {
22
+ return null;
23
+ }
24
+ const handlersContent = `/**
25
+ * ${confirmedValues.displayName} - Service Handlers
26
+ *
27
+ * Generated by Clodo Framework GenerationEngine
28
+ * Service Type: ${coreInputs.serviceType}
29
+ */
30
+
31
+ import { healthCheckResponseSchema, errorResponseSchema } from '../schemas/service-schema.js';
32
+
33
+ export function createServiceHandlers(serviceConfig, env) {
34
+ return {
35
+ async handleRequest(request, ctx) {
36
+ const url = new URL(request.url);
37
+ const path = url.pathname;
38
+
39
+ // Health check endpoint
40
+ if (path === '${confirmedValues.healthCheckPath}') {
41
+ return this.handleHealthCheck(request, serviceConfig);
42
+ }
43
+
44
+ // API routes
45
+ if (path.startsWith('${confirmedValues.apiBasePath}')) {
46
+ return this.handleApiRequest(request, ctx, serviceConfig, env);
47
+ }
48
+
49
+ // Default 404 response
50
+ return new Response(JSON.stringify({
51
+ error: 'Not Found',
52
+ message: \`Endpoint not found: \${path}\`,
53
+ availableEndpoints: [
54
+ '${confirmedValues.healthCheckPath}',
55
+ '${confirmedValues.apiBasePath}/*'
56
+ ]
57
+ }), {
58
+ status: 404,
59
+ headers: { 'Content-Type': 'application/json' }
60
+ });
61
+ },
62
+
63
+ async handleHealthCheck(request, serviceConfig) {
64
+ try {
65
+ // Perform health checks
66
+ const healthStatus = await this.performHealthChecks(serviceConfig, env);
67
+
68
+ const response = {
69
+ status: healthStatus.overall === 'healthy' ? 'healthy' : 'unhealthy',
70
+ timestamp: new Date().toISOString(),
71
+ service: serviceConfig.name,
72
+ version: '${confirmedValues.version}',
73
+ environment: '${coreInputs.environment}',
74
+ checks: healthStatus.checks
75
+ };
76
+
77
+ return new Response(JSON.stringify(response), {
78
+ status: healthStatus.overall === 'healthy' ? 200 : 503,
79
+ headers: { 'Content-Type': 'application/json' }
80
+ });
81
+ } catch (error) {
82
+ return new Response(JSON.stringify({
83
+ status: 'unhealthy',
84
+ timestamp: new Date().toISOString(),
85
+ service: serviceConfig.name,
86
+ error: error.message
87
+ }), {
88
+ status: 503,
89
+ headers: { 'Content-Type': 'application/json' }
90
+ });
91
+ }
92
+ },
93
+
94
+ async handleApiRequest(request, ctx, serviceConfig, env) {
95
+ try {
96
+ const url = new URL(request.url);
97
+ const path = url.pathname.replace('${confirmedValues.apiBasePath}', '');
98
+
99
+ // Route to service-specific handlers
100
+ switch (request.method) {
101
+ case 'GET':
102
+ return this.handleGet(path, request, ctx, serviceConfig, env);
103
+ case 'POST':
104
+ return this.handlePost(path, request, ctx, serviceConfig, env);
105
+ case 'PUT':
106
+ return this.handlePut(path, request, ctx, serviceConfig, env);
107
+ case 'DELETE':
108
+ return this.handleDelete(path, request, ctx, serviceConfig, env);
109
+ default:
110
+ return new Response(JSON.stringify({
111
+ error: 'Method Not Allowed',
112
+ message: \`Method \${request.method} not supported\`
113
+ }), {
114
+ status: 405,
115
+ headers: { 'Content-Type': 'application/json' }
116
+ });
117
+ }
118
+ } catch (error) {
119
+ return new Response(JSON.stringify({
120
+ error: 'Internal Server Error',
121
+ message: error.message,
122
+ timestamp: new Date().toISOString()
123
+ }), {
124
+ status: 500,
125
+ headers: { 'Content-Type': 'application/json' }
126
+ });
127
+ }
128
+ },
129
+
130
+ async performHealthChecks(serviceConfig, env) {
131
+ const checks = [];
132
+
133
+ // Database connectivity check
134
+ try {
135
+ ${confirmedValues.features.database ? `
136
+ // Check database connection
137
+ const dbCheck = await env.DB.prepare('SELECT 1 as health_check').first();
138
+ checks.push({
139
+ name: 'database',
140
+ status: dbCheck ? 'healthy' : 'unhealthy',
141
+ responseTime: Date.now()
142
+ });` : `
143
+ checks.push({
144
+ name: 'database',
145
+ status: 'disabled',
146
+ message: 'Database not configured for this service type'
147
+ });`}
148
+ } catch (error) {
149
+ checks.push({
150
+ name: 'database',
151
+ status: 'unhealthy',
152
+ error: error.message
153
+ });
154
+ }
155
+
156
+ // Service configuration check
157
+ checks.push({
158
+ name: 'configuration',
159
+ status: serviceConfig ? 'healthy' : 'unhealthy',
160
+ message: serviceConfig ? 'Service configuration loaded' : 'Service configuration missing'
161
+ });
162
+
163
+ // Overall health status
164
+ const overall = checks.every(check => check.status === 'healthy' || check.status === 'disabled')
165
+ ? 'healthy' : 'unhealthy';
166
+
167
+ return { overall, checks };
168
+ },
169
+
170
+ // Placeholder handlers - implement based on service type
171
+ async handleGet(path, request, ctx, serviceConfig, env) {
172
+ return new Response(JSON.stringify({
173
+ message: 'GET handler not implemented',
174
+ path,
175
+ service: serviceConfig.name,
176
+ timestamp: new Date().toISOString()
177
+ }), {
178
+ headers: { 'Content-Type': 'application/json' }
179
+ });
180
+ },
181
+
182
+ async handlePost(path, request, ctx, serviceConfig, env) {
183
+ return new Response(JSON.stringify({
184
+ message: 'POST handler not implemented',
185
+ path,
186
+ service: serviceConfig.name,
187
+ timestamp: new Date().toISOString()
188
+ }), {
189
+ headers: { 'Content-Type': 'application/json' }
190
+ });
191
+ },
192
+
193
+ async handlePut(path, request, ctx, serviceConfig, env) {
194
+ return new Response(JSON.stringify({
195
+ message: 'PUT handler not implemented',
196
+ path,
197
+ service: serviceConfig.name,
198
+ timestamp: new Date().toISOString()
199
+ }), {
200
+ headers: { 'Content-Type': 'application/json' }
201
+ });
202
+ },
203
+
204
+ async handleDelete(path, request, ctx, serviceConfig, env) {
205
+ return new Response(JSON.stringify({
206
+ message: 'DELETE handler not implemented',
207
+ path,
208
+ service: serviceConfig.name,
209
+ timestamp: new Date().toISOString()
210
+ }), {
211
+ headers: { 'Content-Type': 'application/json' }
212
+ });
213
+ }
214
+ };
215
+ }
216
+ `;
217
+ const filePath = join(servicePath, 'src', 'handlers', 'service-handlers.js');
218
+
219
+ // Ensure directory exists
220
+ const dir = join(servicePath, 'src', 'handlers');
221
+ mkdirSync(dir, {
222
+ recursive: true
223
+ });
224
+ writeFileSync(filePath, handlersContent, 'utf8');
225
+ this.logger.info(`Generated: ${filePath}`);
226
+ return filePath;
227
+ }
228
+
229
+ /**
230
+ * Determine if generator should run
231
+ */
232
+ shouldGenerate(context) {
233
+ return true; // Always generate handlers
234
+ }
235
+ }
@@ -0,0 +1,116 @@
1
+ import { BaseGenerator } from '../BaseGenerator.js';
2
+ import { join } from 'path';
3
+ import { mkdirSync, writeFileSync } from 'fs';
4
+
5
+ /**
6
+ * Service Middleware Generator
7
+ * Generates middleware functions for request/response processing
8
+ */
9
+ export class ServiceMiddlewareGenerator extends BaseGenerator {
10
+ /**
11
+ * Generate service middleware
12
+ * @param {Object} context - Generation context
13
+ * @returns {Promise<string>} Path to generated middleware file
14
+ */
15
+ async generate(context) {
16
+ const {
17
+ coreInputs,
18
+ confirmedValues,
19
+ servicePath
20
+ } = this.extractContext(context);
21
+ if (!this.shouldGenerate(context)) {
22
+ return null;
23
+ }
24
+ const middlewareContent = `/**
25
+ * ${confirmedValues.displayName} - Service Middleware
26
+ *
27
+ * Generated by Clodo Framework GenerationEngine
28
+ * Service Type: ${coreInputs.serviceType}
29
+ */
30
+
31
+ export function createServiceMiddleware(serviceConfig, env) {
32
+ return {
33
+ async processRequest(request) {
34
+ let processedRequest = request;
35
+
36
+ // Add service context headers
37
+ const headers = new Headers(request.headers);
38
+ headers.set('X-Service', serviceConfig.name);
39
+ headers.set('X-Version', '${confirmedValues.version}');
40
+ headers.set('X-Environment', '${coreInputs.environment}');
41
+ headers.set('X-Request-ID', crypto.randomUUID());
42
+
43
+ // CORS headers for API requests
44
+ if (request.url.includes('${confirmedValues.apiBasePath}')) {
45
+ headers.set('Access-Control-Allow-Origin', '*');
46
+ headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
47
+ headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
48
+ }
49
+
50
+ ${confirmedValues.features.logging ? `
51
+ // Request logging
52
+ console.log(\`[\${new Date().toISOString()}] \${request.method} \${request.url}\`);` : ''}
53
+
54
+ ${confirmedValues.features.rateLimiting ? `
55
+ // Rate limiting (placeholder - implement based on requirements)
56
+ // This would typically check request frequency and block if over limit` : ''}
57
+
58
+ ${confirmedValues.features.authentication ? `
59
+ // Authentication middleware (placeholder)
60
+ // This would validate JWT tokens, API keys, etc.` : ''}
61
+
62
+ ${confirmedValues.features.authorization ? `
63
+ // Authorization middleware (placeholder)
64
+ // This would check user permissions and roles` : ''}
65
+
66
+ return new Request(request.url, {
67
+ ...request,
68
+ headers
69
+ });
70
+ },
71
+
72
+ async processResponse(response) {
73
+ const headers = new Headers(response.headers);
74
+
75
+ // Add standard response headers
76
+ headers.set('X-Service', serviceConfig.name);
77
+ headers.set('X-Version', '${confirmedValues.version}');
78
+ headers.set('X-Response-Time', Date.now().toString());
79
+
80
+ ${confirmedValues.features.monitoring ? `
81
+ // Response monitoring
82
+ console.log(\`Response: \${response.status} (\${Date.now()}ms)\`);` : ''}
83
+
84
+ ${confirmedValues.features.caching ? `
85
+ // Cache headers (placeholder - implement based on content type)
86
+ if (response.status === 200) {
87
+ headers.set('Cache-Control', 'public, max-age=300'); // 5 minutes
88
+ }` : ''}
89
+
90
+ return new Response(response.body, {
91
+ ...response,
92
+ headers
93
+ });
94
+ }
95
+ };
96
+ }
97
+ `;
98
+ const filePath = join(servicePath, 'src', 'middleware', 'service-middleware.js');
99
+
100
+ // Ensure directory exists
101
+ const dir = join(servicePath, 'src', 'middleware');
102
+ mkdirSync(dir, {
103
+ recursive: true
104
+ });
105
+ writeFileSync(filePath, middlewareContent, 'utf8');
106
+ this.logger.info(`Generated: ${filePath}`);
107
+ return filePath;
108
+ }
109
+
110
+ /**
111
+ * Determine if generator should run
112
+ */
113
+ shouldGenerate(context) {
114
+ return true; // Always generate middleware
115
+ }
116
+ }
@@ -0,0 +1,246 @@
1
+ import { BaseGenerator } from '../BaseGenerator.js';
2
+ import { join } from 'path';
3
+ import { mkdirSync, writeFileSync } from 'fs';
4
+
5
+ /**
6
+ * Service Utils Generator
7
+ * Generates utility classes for database, validation, responses, logging, and features
8
+ */
9
+ export class ServiceUtilsGenerator extends BaseGenerator {
10
+ /**
11
+ * Generate service utilities
12
+ * @param {Object} context - Generation context
13
+ * @returns {Promise<string>} Path to generated utils file
14
+ */
15
+ async generate(context) {
16
+ const {
17
+ coreInputs,
18
+ confirmedValues,
19
+ servicePath
20
+ } = this.extractContext(context);
21
+ if (!this.shouldGenerate(context)) {
22
+ return null;
23
+ }
24
+ const utilsContent = `/**
25
+ * ${confirmedValues.displayName} - Service Utilities
26
+ *
27
+ * Generated by Clodo Framework GenerationEngine
28
+ * Service Type: ${coreInputs.serviceType}
29
+ */
30
+
31
+ /**
32
+ * Utility functions for ${confirmedValues.displayName}
33
+ */
34
+
35
+ // Database utilities
36
+ export class DatabaseUtils {
37
+ static async executeQuery(env, query, params = []) {
38
+ try {
39
+ const stmt = env.DB.prepare(query);
40
+ if (params.length > 0) {
41
+ return await stmt.bind(...params).all();
42
+ }
43
+ return await stmt.all();
44
+ } catch (error) {
45
+ console.error('Database query error:', error);
46
+ throw new Error(\`Database operation failed: \${error.message}\`);
47
+ }
48
+ }
49
+
50
+ static async getById(env, table, id) {
51
+ const result = await this.executeQuery(
52
+ env,
53
+ \`SELECT * FROM \${table} WHERE id = ?\`,
54
+ [id]
55
+ );
56
+ return result.results[0] || null;
57
+ }
58
+
59
+ static async create(env, table, data) {
60
+ const columns = Object.keys(data).join(', ');
61
+ const placeholders = Object.keys(data).map(() => '?').join(', ');
62
+ const values = Object.values(data);
63
+
64
+ const result = await this.executeQuery(
65
+ env,
66
+ \`INSERT INTO \${table} (\${columns}) VALUES (\${placeholders})\`,
67
+ values
68
+ );
69
+
70
+ return result.meta.last_row_id;
71
+ }
72
+
73
+ static async update(env, table, id, data) {
74
+ const setClause = Object.keys(data).map(key => \`\${key} = ?\`).join(', ');
75
+ const values = [...Object.values(data), id];
76
+
77
+ const result = await this.executeQuery(
78
+ env,
79
+ \`UPDATE \${table} SET \${setClause} WHERE id = ?\`,
80
+ values
81
+ );
82
+
83
+ return result.meta.changes > 0;
84
+ }
85
+
86
+ static async delete(env, table, id) {
87
+ const result = await this.executeQuery(
88
+ env,
89
+ \`DELETE FROM \${table} WHERE id = ?\`,
90
+ [id]
91
+ );
92
+
93
+ return result.meta.changes > 0;
94
+ }
95
+ }
96
+
97
+ // Validation utilities
98
+ export class ValidationUtils {
99
+ static isValidUUID(uuid) {
100
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
101
+ return uuidRegex.test(uuid);
102
+ }
103
+
104
+ static isValidEmail(email) {
105
+ const emailRegex = /^[^@]+@[^@]+.[^@]+$/;
106
+ return emailRegex.test(email);
107
+ }
108
+
109
+ static sanitizeString(str, maxLength = 1000) {
110
+ if (typeof str !== 'string') return '';
111
+ return str.trim().substring(0, maxLength);
112
+ }
113
+
114
+ static validatePagination(limit = 20, offset = 0) {
115
+ const maxLimit = 100;
116
+ const sanitizedLimit = Math.min(Math.max(1, limit), maxLimit);
117
+ const sanitizedOffset = Math.max(0, offset);
118
+
119
+ return { limit: sanitizedLimit, offset: sanitizedOffset };
120
+ }
121
+ }
122
+
123
+ // Response utilities
124
+ export class ResponseUtils {
125
+ static createSuccessResponse(data, status = 200) {
126
+ return new Response(JSON.stringify({
127
+ success: true,
128
+ data,
129
+ timestamp: new Date().toISOString()
130
+ }), {
131
+ status,
132
+ headers: { 'Content-Type': 'application/json' }
133
+ });
134
+ }
135
+
136
+ static createErrorResponse(error, status = 500, details = null) {
137
+ const errorResponse = {
138
+ success: false,
139
+ error: error.message || 'Internal Server Error',
140
+ timestamp: new Date().toISOString()
141
+ };
142
+
143
+ if (details) {
144
+ errorResponse.details = details;
145
+ }
146
+
147
+ return new Response(JSON.stringify(errorResponse), {
148
+ status,
149
+ headers: { 'Content-Type': 'application/json' }
150
+ });
151
+ }
152
+
153
+ static createPaginatedResponse(data, pagination, status = 200) {
154
+ return new Response(JSON.stringify({
155
+ success: true,
156
+ data,
157
+ pagination: {
158
+ ...pagination,
159
+ hasMore: data.length === pagination.limit
160
+ },
161
+ timestamp: new Date().toISOString()
162
+ }), {
163
+ status,
164
+ headers: { 'Content-Type': 'application/json' }
165
+ });
166
+ }
167
+ }
168
+
169
+ // Logging utilities
170
+ export class LoggingUtils {
171
+ static logRequest(request, context = {}) {
172
+ console.log(JSON.stringify({
173
+ timestamp: new Date().toISOString(),
174
+ level: 'info',
175
+ type: 'request',
176
+ method: request.method,
177
+ url: request.url,
178
+ userAgent: request.headers.get('User-Agent'),
179
+ ...context
180
+ }));
181
+ }
182
+
183
+ static logError(error, context = {}) {
184
+ console.error(JSON.stringify({
185
+ timestamp: new Date().toISOString(),
186
+ level: 'error',
187
+ type: 'error',
188
+ message: error.message,
189
+ stack: error.stack,
190
+ ...context
191
+ }));
192
+ }
193
+
194
+ static logPerformance(operation, startTime, context = {}) {
195
+ const duration = Date.now() - startTime;
196
+ console.log(JSON.stringify({
197
+ timestamp: new Date().toISOString(),
198
+ level: 'info',
199
+ type: 'performance',
200
+ operation,
201
+ duration,
202
+ ...context
203
+ }));
204
+ }
205
+ }
206
+
207
+ // Feature flag utilities
208
+ export class FeatureUtils {
209
+ static isFeatureEnabled(featureName, serviceConfig) {
210
+ return serviceConfig.features && serviceConfig.features[featureName] === true;
211
+ }
212
+
213
+ static getEnabledFeatures(serviceConfig) {
214
+ if (!serviceConfig.features) return [];
215
+ return Object.entries(serviceConfig.features)
216
+ .filter(([, enabled]) => enabled)
217
+ .map(([feature]) => feature);
218
+ }
219
+
220
+ static getDisabledFeatures(serviceConfig) {
221
+ if (!serviceConfig.features) return [];
222
+ return Object.entries(serviceConfig.features)
223
+ .filter(([, enabled]) => !enabled)
224
+ .map(([feature]) => feature);
225
+ }
226
+ }
227
+ `;
228
+ const filePath = join(servicePath, 'src', 'utils', 'service-utils.js');
229
+
230
+ // Ensure directory exists
231
+ const dir = join(servicePath, 'src', 'utils');
232
+ mkdirSync(dir, {
233
+ recursive: true
234
+ });
235
+ writeFileSync(filePath, utilsContent, 'utf8');
236
+ this.logger.info(`Generated: ${filePath}`);
237
+ return filePath;
238
+ }
239
+
240
+ /**
241
+ * Determine if generator should run
242
+ */
243
+ shouldGenerate(context) {
244
+ return true; // Always generate utils
245
+ }
246
+ }