@friggframework/devtools 2.0.0-next.45 → 2.0.0-next.47

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 (212) hide show
  1. package/infrastructure/ARCHITECTURE.md +487 -0
  2. package/infrastructure/HEALTH.md +468 -0
  3. package/infrastructure/README.md +51 -0
  4. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  5. package/infrastructure/__tests__/template-generation.test.js +687 -0
  6. package/infrastructure/create-frigg-infrastructure.js +1 -1
  7. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  8. package/infrastructure/{DEPLOYMENT-INSTRUCTIONS.md → docs/deployment-instructions.md} +3 -3
  9. package/infrastructure/{IAM-POLICY-TEMPLATES.md → docs/iam-policy-templates.md} +9 -10
  10. package/infrastructure/domains/database/aurora-builder.js +809 -0
  11. package/infrastructure/domains/database/aurora-builder.test.js +950 -0
  12. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  13. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  14. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  15. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  16. package/infrastructure/domains/database/migration-builder.js +695 -0
  17. package/infrastructure/domains/database/migration-builder.test.js +294 -0
  18. package/infrastructure/domains/database/migration-resolver.js +163 -0
  19. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  20. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  21. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  22. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  23. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  24. package/infrastructure/domains/health/application/ports/index.js +26 -0
  25. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  26. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  27. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  28. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  29. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  30. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  31. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  32. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  33. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  34. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  35. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  36. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  37. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  38. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  39. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  40. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  41. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  42. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  43. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  44. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  45. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  46. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  47. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  48. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  49. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  50. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  51. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  52. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  53. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  54. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  55. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  56. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  57. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  58. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  59. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  60. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  61. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  62. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  63. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  64. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  65. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  66. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  67. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  68. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  69. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  70. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  71. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  72. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  73. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  74. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  75. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  76. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  77. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  78. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  79. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  80. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  81. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  82. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  83. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  84. package/infrastructure/domains/integration/integration-builder.js +397 -0
  85. package/infrastructure/domains/integration/integration-builder.test.js +593 -0
  86. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  87. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  88. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  89. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  90. package/infrastructure/domains/networking/vpc-builder.js +1829 -0
  91. package/infrastructure/domains/networking/vpc-builder.test.js +1262 -0
  92. package/infrastructure/domains/networking/vpc-discovery.js +177 -0
  93. package/infrastructure/domains/networking/vpc-discovery.test.js +350 -0
  94. package/infrastructure/domains/networking/vpc-resolver.js +324 -0
  95. package/infrastructure/domains/networking/vpc-resolver.test.js +501 -0
  96. package/infrastructure/domains/parameters/ssm-builder.js +79 -0
  97. package/infrastructure/domains/parameters/ssm-builder.test.js +189 -0
  98. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  99. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  100. package/infrastructure/{iam-generator.js → domains/security/iam-generator.js} +2 -2
  101. package/infrastructure/domains/security/kms-builder.js +366 -0
  102. package/infrastructure/domains/security/kms-builder.test.js +374 -0
  103. package/infrastructure/domains/security/kms-discovery.js +80 -0
  104. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  105. package/infrastructure/domains/security/kms-resolver.js +96 -0
  106. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  107. package/infrastructure/domains/shared/base-builder.js +112 -0
  108. package/infrastructure/domains/shared/base-resolver.js +186 -0
  109. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  110. package/infrastructure/domains/shared/builder-orchestrator.js +212 -0
  111. package/infrastructure/domains/shared/builder-orchestrator.test.js +213 -0
  112. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  113. package/infrastructure/domains/shared/cloudformation-discovery.js +375 -0
  114. package/infrastructure/domains/shared/cloudformation-discovery.test.js +590 -0
  115. package/infrastructure/domains/shared/environment-builder.js +119 -0
  116. package/infrastructure/domains/shared/environment-builder.test.js +247 -0
  117. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +544 -0
  118. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +377 -0
  119. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  120. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  121. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  122. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  123. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  124. package/infrastructure/domains/shared/resource-discovery.js +192 -0
  125. package/infrastructure/domains/shared/resource-discovery.test.js +552 -0
  126. package/infrastructure/domains/shared/types/app-definition.js +205 -0
  127. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  128. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  129. package/infrastructure/domains/shared/types/index.js +46 -0
  130. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  131. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  132. package/infrastructure/domains/shared/utilities/base-definition-factory.js +380 -0
  133. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  134. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +248 -0
  135. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  136. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  137. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +55 -0
  138. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +138 -0
  139. package/infrastructure/{env-validator.js → domains/shared/validation/env-validator.js} +2 -1
  140. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  141. package/infrastructure/esbuild.config.js +53 -0
  142. package/infrastructure/infrastructure-composer.js +87 -0
  143. package/infrastructure/{serverless-template.test.js → infrastructure-composer.test.js} +115 -24
  144. package/infrastructure/scripts/build-prisma-layer.js +553 -0
  145. package/infrastructure/scripts/build-prisma-layer.test.js +102 -0
  146. package/infrastructure/{build-time-discovery.js → scripts/build-time-discovery.js} +80 -48
  147. package/infrastructure/{build-time-discovery.test.js → scripts/build-time-discovery.test.js} +5 -4
  148. package/layers/prisma/nodejs/package.json +8 -0
  149. package/management-ui/server/utils/cliIntegration.js +1 -1
  150. package/management-ui/server/utils/environment/awsParameterStore.js +29 -18
  151. package/package.json +11 -11
  152. package/frigg-cli/.eslintrc.js +0 -141
  153. package/frigg-cli/__tests__/unit/commands/build.test.js +0 -251
  154. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +0 -548
  155. package/frigg-cli/__tests__/unit/commands/install.test.js +0 -400
  156. package/frigg-cli/__tests__/unit/commands/ui.test.js +0 -346
  157. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +0 -366
  158. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +0 -304
  159. package/frigg-cli/__tests__/unit/utils/prisma-runner.test.js +0 -486
  160. package/frigg-cli/__tests__/utils/mock-factory.js +0 -270
  161. package/frigg-cli/__tests__/utils/prisma-mock.js +0 -194
  162. package/frigg-cli/__tests__/utils/test-fixtures.js +0 -463
  163. package/frigg-cli/__tests__/utils/test-setup.js +0 -287
  164. package/frigg-cli/build-command/index.js +0 -65
  165. package/frigg-cli/db-setup-command/index.js +0 -193
  166. package/frigg-cli/deploy-command/index.js +0 -175
  167. package/frigg-cli/generate-command/__tests__/generate-command.test.js +0 -301
  168. package/frigg-cli/generate-command/azure-generator.js +0 -43
  169. package/frigg-cli/generate-command/gcp-generator.js +0 -47
  170. package/frigg-cli/generate-command/index.js +0 -332
  171. package/frigg-cli/generate-command/terraform-generator.js +0 -555
  172. package/frigg-cli/generate-iam-command.js +0 -118
  173. package/frigg-cli/index.js +0 -75
  174. package/frigg-cli/index.test.js +0 -158
  175. package/frigg-cli/init-command/backend-first-handler.js +0 -756
  176. package/frigg-cli/init-command/index.js +0 -93
  177. package/frigg-cli/init-command/template-handler.js +0 -143
  178. package/frigg-cli/install-command/backend-js.js +0 -33
  179. package/frigg-cli/install-command/commit-changes.js +0 -16
  180. package/frigg-cli/install-command/environment-variables.js +0 -127
  181. package/frigg-cli/install-command/environment-variables.test.js +0 -136
  182. package/frigg-cli/install-command/index.js +0 -54
  183. package/frigg-cli/install-command/install-package.js +0 -13
  184. package/frigg-cli/install-command/integration-file.js +0 -30
  185. package/frigg-cli/install-command/logger.js +0 -12
  186. package/frigg-cli/install-command/template.js +0 -90
  187. package/frigg-cli/install-command/validate-package.js +0 -75
  188. package/frigg-cli/jest.config.js +0 -124
  189. package/frigg-cli/package.json +0 -54
  190. package/frigg-cli/start-command/index.js +0 -149
  191. package/frigg-cli/start-command/start-command.test.js +0 -297
  192. package/frigg-cli/test/init-command.test.js +0 -180
  193. package/frigg-cli/test/npm-registry.test.js +0 -319
  194. package/frigg-cli/ui-command/index.js +0 -154
  195. package/frigg-cli/utils/app-resolver.js +0 -319
  196. package/frigg-cli/utils/backend-path.js +0 -25
  197. package/frigg-cli/utils/database-validator.js +0 -161
  198. package/frigg-cli/utils/error-messages.js +0 -257
  199. package/frigg-cli/utils/npm-registry.js +0 -167
  200. package/frigg-cli/utils/prisma-runner.js +0 -280
  201. package/frigg-cli/utils/process-manager.js +0 -199
  202. package/frigg-cli/utils/repo-detection.js +0 -405
  203. package/infrastructure/aws-discovery.js +0 -1176
  204. package/infrastructure/aws-discovery.test.js +0 -1220
  205. package/infrastructure/serverless-template.js +0 -2094
  206. /package/infrastructure/{WEBSOCKET-CONFIGURATION.md → docs/WEBSOCKET-CONFIGURATION.md} +0 -0
  207. /package/infrastructure/{GENERATE-IAM-DOCS.md → docs/generate-iam-command.md} +0 -0
  208. /package/infrastructure/{iam-generator.test.js → domains/security/iam-generator.test.js} +0 -0
  209. /package/infrastructure/{frigg-deployment-iam-stack.yaml → domains/security/templates/frigg-deployment-iam-stack.yaml} +0 -0
  210. /package/infrastructure/{iam-policy-basic.json → domains/security/templates/iam-policy-basic.json} +0 -0
  211. /package/infrastructure/{iam-policy-full.json → domains/security/templates/iam-policy-full.json} +0 -0
  212. /package/infrastructure/{run-discovery.js → scripts/run-discovery.js} +0 -0
@@ -0,0 +1,777 @@
1
+ /**
2
+ * AWSStackRepository - AWS CloudFormation Stack Adapter
3
+ *
4
+ * Infrastructure Adapter - Hexagonal Architecture
5
+ *
6
+ * Implements IStackRepository port for AWS CloudFormation.
7
+ * Handles CloudFormation API operations using AWS SDK v3.
8
+ *
9
+ * Lazy-loads AWS SDK to minimize cold start time and memory usage.
10
+ */
11
+
12
+ const IStackRepository = require('../../application/ports/IStackRepository');
13
+ const yaml = require('js-yaml');
14
+
15
+ // Lazy-loaded AWS SDK CloudFormation client
16
+ let CloudFormationClient,
17
+ DescribeStacksCommand,
18
+ ListStackResourcesCommand,
19
+ DescribeStackResourcesCommand,
20
+ DescribeStackResourceCommand,
21
+ GetTemplateCommand,
22
+ DetectStackDriftCommand,
23
+ DescribeStackDriftDetectionStatusCommand,
24
+ DescribeStackResourceDriftsCommand,
25
+ CreateChangeSetCommand,
26
+ DescribeChangeSetCommand,
27
+ ExecuteChangeSetCommand,
28
+ DescribeStackEventsCommand;
29
+
30
+ // Lazy-loaded AWS SDK S3 client for large template uploads
31
+ let S3Client, PutObjectCommand;
32
+
33
+ /**
34
+ * Lazy load CloudFormation SDK
35
+ */
36
+ function loadCloudFormation() {
37
+ if (!CloudFormationClient) {
38
+ const cfModule = require('@aws-sdk/client-cloudformation');
39
+ CloudFormationClient = cfModule.CloudFormationClient;
40
+ DescribeStacksCommand = cfModule.DescribeStacksCommand;
41
+ ListStackResourcesCommand = cfModule.ListStackResourcesCommand;
42
+ DescribeStackResourcesCommand = cfModule.DescribeStackResourcesCommand;
43
+ DescribeStackResourceCommand = cfModule.DescribeStackResourceCommand;
44
+ GetTemplateCommand = cfModule.GetTemplateCommand;
45
+ DetectStackDriftCommand = cfModule.DetectStackDriftCommand;
46
+ DescribeStackDriftDetectionStatusCommand =
47
+ cfModule.DescribeStackDriftDetectionStatusCommand;
48
+ DescribeStackResourceDriftsCommand = cfModule.DescribeStackResourceDriftsCommand;
49
+ CreateChangeSetCommand = cfModule.CreateChangeSetCommand;
50
+ DescribeChangeSetCommand = cfModule.DescribeChangeSetCommand;
51
+ ExecuteChangeSetCommand = cfModule.ExecuteChangeSetCommand;
52
+ DescribeStackEventsCommand = cfModule.DescribeStackEventsCommand;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Lazy load S3 SDK for template uploads
58
+ */
59
+ function loadS3() {
60
+ if (!S3Client) {
61
+ const s3Module = require('@aws-sdk/client-s3');
62
+ S3Client = s3Module.S3Client;
63
+ PutObjectCommand = s3Module.PutObjectCommand;
64
+ }
65
+ }
66
+
67
+ class AWSStackRepository extends IStackRepository {
68
+ /**
69
+ * Create AWS Stack Repository
70
+ *
71
+ * @param {Object} [config={}]
72
+ * @param {string} [config.region] - AWS region (defaults to AWS_REGION env var)
73
+ */
74
+ constructor(config = {}) {
75
+ super();
76
+ this.region = config.region || process.env.AWS_REGION || 'us-east-1';
77
+ this.client = null;
78
+ this.s3Client = null;
79
+ // S3 bucket for large template uploads (defaults to serverless deployment bucket)
80
+ this.templateBucket = config.templateBucket || null;
81
+ }
82
+
83
+ /**
84
+ * Get or create CloudFormation client
85
+ * @private
86
+ */
87
+ _getClient() {
88
+ if (!this.client) {
89
+ loadCloudFormation();
90
+ this.client = new CloudFormationClient({ region: this.region });
91
+ }
92
+ return this.client;
93
+ }
94
+
95
+ /**
96
+ * Get or create S3 client
97
+ * @private
98
+ */
99
+ _getS3Client() {
100
+ if (!this.s3Client) {
101
+ loadS3();
102
+ this.s3Client = new S3Client({ region: this.region });
103
+ }
104
+ return this.s3Client;
105
+ }
106
+
107
+ /**
108
+ * Upload CloudFormation template to S3 (public API)
109
+ *
110
+ * Exposed as public method for use by other adapters that need to upload
111
+ * templates to S3 before calling UpdateStack/CreateChangeSet.
112
+ *
113
+ * @param {Object} params - Upload parameters
114
+ * @param {string} params.stackName - Stack name for S3 key prefix
115
+ * @param {string} params.templateBody - CloudFormation template JSON string
116
+ * @returns {Promise<string>} S3 URL for uploaded template
117
+ */
118
+ async uploadTemplate({ stackName, templateBody }) {
119
+ return await this._uploadTemplateToS3({ stackName, templateBody });
120
+ }
121
+
122
+ /**
123
+ * Upload template to S3 for large templates (> 51,200 bytes) - Internal implementation
124
+ *
125
+ * @param {Object} params - Upload parameters
126
+ * @param {string} params.stackName - Stack name for S3 key prefix
127
+ * @param {string} params.templateBody - CloudFormation template JSON string
128
+ * @returns {Promise<string>} S3 URL for uploaded template
129
+ * @private
130
+ */
131
+ async _uploadTemplateToS3({ stackName, templateBody }) {
132
+ const s3Client = this._getS3Client();
133
+
134
+ // Get serverless deployment bucket from stack if not configured
135
+ if (!this.templateBucket) {
136
+ try {
137
+ const stacks = await this._getClient().send(
138
+ new DescribeStacksCommand({ StackName: stackName })
139
+ );
140
+
141
+ // Look for ServerlessDeploymentBucket output
142
+ const bucket = stacks.Stacks[0]?.Outputs?.find(
143
+ o => o.OutputKey === 'ServerlessDeploymentBucketName'
144
+ )?.OutputValue;
145
+
146
+ if (bucket) {
147
+ this.templateBucket = bucket;
148
+ } else {
149
+ throw new Error('No S3 bucket configured for template uploads. Set templateBucket in config or ensure ServerlessDeploymentBucket exists.');
150
+ }
151
+ } catch (error) {
152
+ throw new Error(`Failed to find S3 bucket for template upload: ${error.message}`);
153
+ }
154
+ }
155
+
156
+ // Generate S3 key with timestamp
157
+ const timestamp = Date.now();
158
+ const key = `cloudformation-templates/${stackName}/import-template-${timestamp}.json`;
159
+
160
+ // Upload to S3
161
+ const putCommand = new PutObjectCommand({
162
+ Bucket: this.templateBucket,
163
+ Key: key,
164
+ Body: templateBody,
165
+ ContentType: 'application/json',
166
+ });
167
+
168
+ await s3Client.send(putCommand);
169
+
170
+ // Return S3 URL
171
+ const s3Url = `https://${this.templateBucket}.s3.${this.region}.amazonaws.com/${key}`;
172
+
173
+ if (process.env.DEBUG_IMPORT_TEMPLATE === 'true') {
174
+ console.log(`[DEBUG] Template uploaded to S3: ${s3Url}`);
175
+ }
176
+
177
+ return s3Url;
178
+ }
179
+
180
+ /**
181
+ * Get stack information by identifier
182
+ */
183
+ async getStack(identifier) {
184
+ const client = this._getClient();
185
+
186
+ try {
187
+ const command = new DescribeStacksCommand({
188
+ StackName: identifier.stackName,
189
+ });
190
+
191
+ const response = await client.send(command);
192
+
193
+ if (!response.Stacks || response.Stacks.length === 0) {
194
+ throw new Error(
195
+ `Stack ${identifier.stackName} does not exist in region ${this.region}`
196
+ );
197
+ }
198
+
199
+ const stack = response.Stacks[0];
200
+
201
+ // Parse ARN to get account ID
202
+ const arnMatch = stack.StackId.match(/:(\d{12}):/);
203
+ const accountId = arnMatch ? arnMatch[1] : identifier.accountId;
204
+
205
+ return {
206
+ stackName: stack.StackName,
207
+ region: this.region,
208
+ accountId,
209
+ stackId: stack.StackId,
210
+ status: stack.StackStatus,
211
+ creationTime: stack.CreationTime,
212
+ lastUpdatedTime: stack.LastUpdatedTime,
213
+ parameters: this._parseParameters(stack.Parameters),
214
+ outputs: this._parseOutputs(stack.Outputs),
215
+ tags: this._parseTags(stack.Tags),
216
+ };
217
+ } catch (error) {
218
+ if (error.name === 'ValidationError' || error.message?.includes('does not exist')) {
219
+ throw new Error(
220
+ `Stack ${identifier.stackName} does not exist in region ${this.region}`
221
+ );
222
+ }
223
+ throw error;
224
+ }
225
+ }
226
+
227
+ /**
228
+ * List all resources in a stack
229
+ */
230
+ async listResources(identifier) {
231
+ const client = this._getClient();
232
+ const resources = [];
233
+ let nextToken = null;
234
+
235
+ do {
236
+ const command = new ListStackResourcesCommand({
237
+ StackName: identifier.stackName,
238
+ NextToken: nextToken,
239
+ });
240
+
241
+ const response = await client.send(command);
242
+
243
+ if (response.StackResourceSummaries) {
244
+ for (const resource of response.StackResourceSummaries) {
245
+ resources.push({
246
+ logicalId: resource.LogicalResourceId,
247
+ physicalId: resource.PhysicalResourceId,
248
+ resourceType: resource.ResourceType,
249
+ status: resource.ResourceStatus,
250
+ lastUpdatedTime: resource.LastUpdatedTimestamp,
251
+ driftStatus: resource.DriftInformation?.StackResourceDriftStatus || 'NOT_CHECKED',
252
+ });
253
+ }
254
+ }
255
+
256
+ nextToken = response.NextToken;
257
+ } while (nextToken);
258
+
259
+ return resources;
260
+ }
261
+
262
+ /**
263
+ * Get resource details from stack
264
+ */
265
+ async getResource(identifier, logicalId) {
266
+ const client = this._getClient();
267
+
268
+ const command = new DescribeStackResourceCommand({
269
+ StackName: identifier.stackName,
270
+ LogicalResourceId: logicalId,
271
+ });
272
+
273
+ const response = await client.send(command);
274
+ const resource = response.StackResourceDetail;
275
+
276
+ return {
277
+ logicalId: resource.LogicalResourceId,
278
+ physicalId: resource.PhysicalResourceId,
279
+ resourceType: resource.ResourceType,
280
+ status: resource.ResourceStatus,
281
+ properties: {}, // CloudFormation doesn't return properties directly
282
+ metadata: this._parseMetadata(resource.Metadata),
283
+ };
284
+ }
285
+
286
+ /**
287
+ * Get the CloudFormation template for a stack
288
+ */
289
+ async getTemplate(identifier) {
290
+ const client = this._getClient();
291
+
292
+ const command = new GetTemplateCommand({
293
+ StackName: identifier.stackName,
294
+ TemplateStage: 'Original',
295
+ });
296
+
297
+ const response = await client.send(command);
298
+ const templateBody = response.TemplateBody;
299
+
300
+ // Try to parse as JSON first
301
+ try {
302
+ return JSON.parse(templateBody);
303
+ } catch {
304
+ // If not JSON, try YAML
305
+ try {
306
+ return yaml.load(templateBody);
307
+ } catch {
308
+ throw new Error('Failed to parse template body as JSON or YAML');
309
+ }
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Check if a stack exists
315
+ */
316
+ async exists(identifier) {
317
+ try {
318
+ const stack = await this.getStack(identifier);
319
+
320
+ // Check if stack is in a deleted state
321
+ const deletedStates = ['DELETE_COMPLETE', 'DELETE_IN_PROGRESS'];
322
+ return !deletedStates.includes(stack.status);
323
+ } catch (error) {
324
+ if (error.message?.includes('does not exist')) {
325
+ return false;
326
+ }
327
+ throw error;
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Detect drift for the entire stack
333
+ */
334
+ async detectStackDrift(identifier) {
335
+ const client = this._getClient();
336
+
337
+ // Initiate drift detection
338
+ const detectCommand = new DetectStackDriftCommand({
339
+ StackName: identifier.stackName,
340
+ });
341
+
342
+ const detectResponse = await client.send(detectCommand);
343
+ const driftDetectionId = detectResponse.StackDriftDetectionId;
344
+
345
+ // Poll for detection completion
346
+ let detectionStatus = 'DETECTION_IN_PROGRESS';
347
+ let statusResponse;
348
+
349
+ while (detectionStatus === 'DETECTION_IN_PROGRESS') {
350
+ await this._sleep(1000); // Wait 1 second between polls
351
+
352
+ const statusCommand = new DescribeStackDriftDetectionStatusCommand({
353
+ StackDriftDetectionId: driftDetectionId,
354
+ });
355
+
356
+ statusResponse = await client.send(statusCommand);
357
+ detectionStatus = statusResponse.DetectionStatus;
358
+ }
359
+
360
+ if (detectionStatus !== 'DETECTION_COMPLETE') {
361
+ throw new Error(`Drift detection failed with status: ${detectionStatus}`);
362
+ }
363
+
364
+ return {
365
+ stackDriftStatus: statusResponse.StackDriftStatus,
366
+ driftedResourceCount: statusResponse.DriftedStackResourceCount || 0,
367
+ detectionTime: statusResponse.Timestamp,
368
+ };
369
+ }
370
+
371
+ /**
372
+ * Get drift details for a specific resource
373
+ */
374
+ async getResourceDrift(identifier, logicalId) {
375
+ const client = this._getClient();
376
+
377
+ const command = new DescribeStackResourceDriftsCommand({
378
+ StackName: identifier.stackName,
379
+ StackResourceDriftStatusFilters: ['MODIFIED', 'DELETED', 'IN_SYNC'],
380
+ });
381
+
382
+ const response = await client.send(command);
383
+
384
+ // Find the specific resource
385
+ const resourceDrift = response.StackResourceDrifts?.find(
386
+ (drift) => drift.LogicalResourceId === logicalId
387
+ );
388
+
389
+ if (!resourceDrift) {
390
+ throw new Error(
391
+ `No drift information found for resource ${logicalId} in stack ${identifier.stackName}`
392
+ );
393
+ }
394
+
395
+ return {
396
+ driftStatus: resourceDrift.StackResourceDriftStatus,
397
+ expectedProperties: this._parseProperties(resourceDrift.ExpectedProperties),
398
+ actualProperties: this._parseProperties(resourceDrift.ActualProperties),
399
+ propertyDifferences: resourceDrift.PropertyDifferences || [],
400
+ };
401
+ }
402
+
403
+ // ========================================
404
+ // CloudFormation Change Set Operations
405
+ // ========================================
406
+
407
+ /**
408
+ * Create CloudFormation change set for import or update
409
+ *
410
+ * @param {Object} params - Change set parameters
411
+ * @param {StackIdentifier} params.stackIdentifier - Stack identifier
412
+ * @param {string} params.changeSetName - Name for the change set
413
+ * @param {string} params.changeSetType - Type of change set ('IMPORT', 'UPDATE', or 'CREATE')
414
+ * @param {Object} params.template - CloudFormation template object
415
+ * @param {Array} [params.resourcesToImport] - Resources to import (required for IMPORT type)
416
+ * @returns {Promise<Object>} Change set result with Id and StackId
417
+ * @throws {Error} If change set creation fails
418
+ */
419
+ async createChangeSet({ stackIdentifier, changeSetName, changeSetType, template, resourcesToImport }) {
420
+ const client = this._getClient();
421
+
422
+ // Ensure template is an object (not already stringified)
423
+ const templateObj = typeof template === 'string' ? JSON.parse(template) : template;
424
+
425
+ // Validate template structure
426
+ if (!templateObj || typeof templateObj !== 'object') {
427
+ throw new Error(`Invalid template: expected object, got ${typeof templateObj}`);
428
+ }
429
+
430
+ if (!templateObj.Resources || typeof templateObj.Resources !== 'object') {
431
+ throw new Error(`Invalid template: missing or invalid Resources section`);
432
+ }
433
+
434
+ // DEBUG: Log template structure if debug enabled
435
+ if (process.env.DEBUG_IMPORT_TEMPLATE === 'true') {
436
+ console.log('[DEBUG] Template structure validation:');
437
+ console.log(' - Top-level keys:', Object.keys(templateObj));
438
+ console.log(' - Resources count:', Object.keys(templateObj.Resources).length);
439
+ console.log(' - Resource types:', {
440
+ ...Object.entries(templateObj.Resources).reduce((acc, [id, def]) => {
441
+ acc[id] = def.Type;
442
+ return acc;
443
+ }, {})
444
+ });
445
+
446
+ if (resourcesToImport) {
447
+ console.log(' - ResourcesToImport:', resourcesToImport.length);
448
+ resourcesToImport.forEach((r, i) => {
449
+ console.log(` ${i + 1}. ${r.LogicalResourceId} (${r.ResourceType})`);
450
+ });
451
+ }
452
+ }
453
+
454
+ const templateBody = JSON.stringify(templateObj, null, 2);
455
+ const templateSize = templateBody.length;
456
+
457
+ // CloudFormation inline template size limit (51,200 bytes)
458
+ const TEMPLATE_SIZE_LIMIT = 51200;
459
+ const useS3 = templateSize > TEMPLATE_SIZE_LIMIT;
460
+
461
+ if (process.env.DEBUG_IMPORT_TEMPLATE === 'true') {
462
+ console.log(`[DEBUG] Template size: ${templateSize} bytes (limit: ${TEMPLATE_SIZE_LIMIT})`);
463
+ console.log(`[DEBUG] Using ${useS3 ? 'S3' : 'inline'} template delivery`);
464
+ }
465
+
466
+ const params = {
467
+ StackName: stackIdentifier.stackName,
468
+ ChangeSetName: changeSetName,
469
+ ChangeSetType: changeSetType,
470
+ // Add IAM capabilities for templates with IAM resources
471
+ Capabilities: ['CAPABILITY_NAMED_IAM'],
472
+ };
473
+
474
+ // Use S3 for large templates, inline for small templates
475
+ if (useS3) {
476
+ const templateUrl = await this._uploadTemplateToS3({
477
+ stackName: stackIdentifier.stackName,
478
+ templateBody,
479
+ });
480
+ params.TemplateURL = templateUrl;
481
+ } else {
482
+ params.TemplateBody = templateBody;
483
+ }
484
+
485
+ // Add resources to import for IMPORT change sets
486
+ if (changeSetType === 'IMPORT') {
487
+ if (!resourcesToImport || resourcesToImport.length === 0) {
488
+ throw new Error('resourcesToImport is required for IMPORT change set type');
489
+ }
490
+ params.ResourcesToImport = resourcesToImport;
491
+ }
492
+
493
+ try {
494
+ const command = new CreateChangeSetCommand(params);
495
+ const response = await client.send(command);
496
+
497
+ return {
498
+ Id: response.Id,
499
+ StackId: response.StackId,
500
+ templateUrl: useS3 ? params.TemplateURL : undefined,
501
+ };
502
+ } catch (error) {
503
+ // Add more context to the error
504
+ if (error.message?.includes('is not expected')) {
505
+ throw new Error(`CloudFormation template format error: ${error.message}. Template size: ${templateSize} bytes, Resources to import: ${resourcesToImport?.length || 0}. Delivery method: ${useS3 ? 'S3' : 'inline'}. First 200 chars: ${templateBody.substring(0, 200)}`);
506
+ }
507
+ throw error;
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Wait for change set to be ready (CREATE_COMPLETE status)
513
+ *
514
+ * @param {Object} params - Wait parameters
515
+ * @param {StackIdentifier} params.stackIdentifier - Stack identifier
516
+ * @param {string} params.changeSetName - Name of the change set
517
+ * @param {number} [params.maxAttempts=60] - Maximum polling attempts
518
+ * @param {number} [params.delayMs=2000] - Delay between polling attempts in milliseconds
519
+ * @returns {Promise<Object>} Change set details when ready
520
+ * @throws {Error} If change set creation fails or times out
521
+ */
522
+ async waitForChangeSet({ stackIdentifier, changeSetName, maxAttempts = 60, delayMs = 2000 }) {
523
+ const client = this._getClient();
524
+
525
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
526
+ const command = new DescribeChangeSetCommand({
527
+ StackName: stackIdentifier.stackName,
528
+ ChangeSetName: changeSetName,
529
+ });
530
+
531
+ const response = await client.send(command);
532
+
533
+ // Check for completion or failure
534
+ // AWS requires BOTH Status and ExecutionStatus checks for import change sets
535
+ if (response.Status === 'CREATE_COMPLETE') {
536
+ // Also verify ExecutionStatus is AVAILABLE (not UNAVAILABLE, EXECUTE_IN_PROGRESS, etc.)
537
+ if (response.ExecutionStatus === 'AVAILABLE') {
538
+ return response;
539
+ } else if (response.ExecutionStatus === 'UNAVAILABLE') {
540
+ throw new Error(
541
+ `Change set cannot be executed: ${response.StatusReason || 'ExecutionStatus is UNAVAILABLE'}`
542
+ );
543
+ }
544
+ // If ExecutionStatus is EXECUTE_IN_PROGRESS or EXECUTE_COMPLETE, continue waiting
545
+ }
546
+
547
+ if (response.Status === 'FAILED') {
548
+ throw new Error(
549
+ `Change set creation failed: ${response.StatusReason || 'Unknown reason'}`
550
+ );
551
+ }
552
+
553
+ // Wait before next attempt
554
+ await this._sleep(delayMs);
555
+ }
556
+
557
+ throw new Error(
558
+ `Change set creation timed out after ${maxAttempts} attempts (${(maxAttempts * delayMs) / 1000}s)`
559
+ );
560
+ }
561
+
562
+ /**
563
+ * Execute a change set
564
+ *
565
+ * @param {Object} params - Execution parameters
566
+ * @param {StackIdentifier} params.stackIdentifier - Stack identifier
567
+ * @param {string} params.changeSetName - Name of the change set to execute
568
+ * @returns {Promise<Object>} Execution result (empty object on success)
569
+ * @throws {Error} If change set execution fails
570
+ */
571
+ async executeChangeSet({ stackIdentifier, changeSetName }) {
572
+ const client = this._getClient();
573
+
574
+ const command = new ExecuteChangeSetCommand({
575
+ StackName: stackIdentifier.stackName,
576
+ ChangeSetName: changeSetName,
577
+ });
578
+
579
+ const response = await client.send(command);
580
+ return response;
581
+ }
582
+
583
+ /**
584
+ * Get stack events since a specific timestamp
585
+ *
586
+ * @param {Object} params - Event query parameters
587
+ * @param {StackIdentifier} params.stackIdentifier - Stack identifier
588
+ * @param {Date} params.since - Timestamp to filter events from
589
+ * @returns {Promise<Array>} Array of stack events sorted chronologically
590
+ * @returns {Promise<Array<Object>>} Array of events with properties:
591
+ * - EventId: string
592
+ * - StackName: string
593
+ * - LogicalResourceId: string
594
+ * - PhysicalResourceId: string
595
+ * - ResourceType: string
596
+ * - Timestamp: Date
597
+ * - ResourceStatus: string
598
+ * - ResourceStatusReason: string
599
+ */
600
+ async getStackEvents({ stackIdentifier, since }) {
601
+ const client = this._getClient();
602
+ const events = [];
603
+ let nextToken = null;
604
+
605
+ do {
606
+ const command = new DescribeStackEventsCommand({
607
+ StackName: stackIdentifier.stackName,
608
+ NextToken: nextToken,
609
+ });
610
+
611
+ const response = await client.send(command);
612
+
613
+ if (response.StackEvents) {
614
+ // Filter events after the 'since' timestamp
615
+ const filteredEvents = response.StackEvents.filter(
616
+ (event) => event.Timestamp > since
617
+ );
618
+ events.push(...filteredEvents);
619
+
620
+ // Stop pagination if we've reached events before 'since'
621
+ if (filteredEvents.length < response.StackEvents.length) {
622
+ break;
623
+ }
624
+ }
625
+
626
+ nextToken = response.NextToken;
627
+ } while (nextToken);
628
+
629
+ // Sort chronologically (oldest first)
630
+ return events.sort((a, b) => a.Timestamp - b.Timestamp);
631
+ }
632
+
633
+ /**
634
+ * Get current stack status
635
+ *
636
+ * @param {StackIdentifier} identifier - Stack identifier
637
+ * @returns {Promise<string>} Stack status (e.g., 'CREATE_COMPLETE', 'UPDATE_IN_PROGRESS')
638
+ * @throws {Error} If stack does not exist
639
+ */
640
+ async getStackStatus(identifier) {
641
+ const client = this._getClient();
642
+
643
+ const command = new DescribeStacksCommand({
644
+ StackName: identifier.stackName,
645
+ });
646
+
647
+ const response = await client.send(command);
648
+
649
+ if (!response.Stacks || response.Stacks.length === 0) {
650
+ throw new Error(
651
+ `Stack ${identifier.stackName} does not exist in region ${this.region}`
652
+ );
653
+ }
654
+
655
+ return response.Stacks[0].StackStatus;
656
+ }
657
+
658
+ /**
659
+ * Get stack resources with detailed information
660
+ *
661
+ * @param {StackIdentifier} identifier - Stack identifier
662
+ * @returns {Promise<Array>} Array of stack resources with full details
663
+ * @returns {Promise<Array<Object>>} Array of resources with properties:
664
+ * - LogicalResourceId: string
665
+ * - PhysicalResourceId: string
666
+ * - ResourceType: string
667
+ * - ResourceStatus: string
668
+ * - Timestamp: Date
669
+ * - DriftInformation: Object (if available)
670
+ * @throws {Error} If stack does not exist
671
+ */
672
+ async getStackResources(identifier) {
673
+ const client = this._getClient();
674
+
675
+ const command = new DescribeStackResourcesCommand({
676
+ StackName: identifier.stackName,
677
+ });
678
+
679
+ const response = await client.send(command);
680
+
681
+ return response.StackResources || [];
682
+ }
683
+
684
+ // ========================================
685
+ // Private Helper Methods
686
+ // ========================================
687
+
688
+ /**
689
+ * Parse CloudFormation parameters to key-value object
690
+ * @private
691
+ */
692
+ _parseParameters(parameters) {
693
+ if (!parameters || parameters.length === 0) {
694
+ return {};
695
+ }
696
+
697
+ const result = {};
698
+ for (const param of parameters) {
699
+ result[param.ParameterKey] = param.ParameterValue;
700
+ }
701
+ return result;
702
+ }
703
+
704
+ /**
705
+ * Parse CloudFormation outputs to key-value object
706
+ * @private
707
+ */
708
+ _parseOutputs(outputs) {
709
+ if (!outputs || outputs.length === 0) {
710
+ return {};
711
+ }
712
+
713
+ const result = {};
714
+ for (const output of outputs) {
715
+ result[output.OutputKey] = output.OutputValue;
716
+ }
717
+ return result;
718
+ }
719
+
720
+ /**
721
+ * Parse CloudFormation tags to key-value object
722
+ * @private
723
+ */
724
+ _parseTags(tags) {
725
+ if (!tags || tags.length === 0) {
726
+ return {};
727
+ }
728
+
729
+ const result = {};
730
+ for (const tag of tags) {
731
+ result[tag.Key] = tag.Value;
732
+ }
733
+ return result;
734
+ }
735
+
736
+ /**
737
+ * Parse resource metadata
738
+ * @private
739
+ */
740
+ _parseMetadata(metadata) {
741
+ if (!metadata) {
742
+ return {};
743
+ }
744
+
745
+ try {
746
+ return JSON.parse(metadata);
747
+ } catch {
748
+ return {};
749
+ }
750
+ }
751
+
752
+ /**
753
+ * Parse property JSON string
754
+ * @private
755
+ */
756
+ _parseProperties(propertiesString) {
757
+ if (!propertiesString) {
758
+ return {};
759
+ }
760
+
761
+ try {
762
+ return JSON.parse(propertiesString);
763
+ } catch {
764
+ return {};
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Sleep for specified milliseconds
770
+ * @private
771
+ */
772
+ _sleep(ms) {
773
+ return new Promise((resolve) => setTimeout(resolve, ms));
774
+ }
775
+ }
776
+
777
+ module.exports = AWSStackRepository;