@friggframework/devtools 2.0.0-next.11 → 2.0.0-next.110

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 (247) hide show
  1. package/frigg-cli/README.md +1289 -0
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +279 -0
  3. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +649 -0
  4. package/frigg-cli/__tests__/unit/commands/deploy.test.js +320 -0
  5. package/frigg-cli/__tests__/unit/commands/doctor.test.js +309 -0
  6. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +97 -0
  7. package/frigg-cli/__tests__/unit/commands/install.test.js +400 -0
  8. package/frigg-cli/__tests__/unit/commands/ui.test.js +346 -0
  9. package/frigg-cli/__tests__/unit/dependencies.test.js +74 -0
  10. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +397 -0
  11. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +345 -0
  12. package/frigg-cli/__tests__/unit/version-detection.test.js +171 -0
  13. package/frigg-cli/__tests__/utils/mock-factory.js +270 -0
  14. package/frigg-cli/__tests__/utils/prisma-mock.js +194 -0
  15. package/frigg-cli/__tests__/utils/test-fixtures.js +463 -0
  16. package/frigg-cli/__tests__/utils/test-setup.js +287 -0
  17. package/frigg-cli/auth-command/CLAUDE.md +293 -0
  18. package/frigg-cli/auth-command/README.md +450 -0
  19. package/frigg-cli/auth-command/api-key-flow.js +153 -0
  20. package/frigg-cli/auth-command/auth-tester.js +344 -0
  21. package/frigg-cli/auth-command/credential-storage.js +182 -0
  22. package/frigg-cli/auth-command/index.js +256 -0
  23. package/frigg-cli/auth-command/json-schema-form.js +67 -0
  24. package/frigg-cli/auth-command/module-loader.js +172 -0
  25. package/frigg-cli/auth-command/oauth-callback-server.js +431 -0
  26. package/frigg-cli/auth-command/oauth-flow.js +195 -0
  27. package/frigg-cli/auth-command/utils/browser.js +30 -0
  28. package/frigg-cli/build-command/index.js +45 -12
  29. package/frigg-cli/db-setup-command/index.js +246 -0
  30. package/frigg-cli/deploy-command/SPEC-DEPLOY-DRY-RUN.md +981 -0
  31. package/frigg-cli/deploy-command/index.js +339 -23
  32. package/frigg-cli/doctor-command/index.js +335 -0
  33. package/frigg-cli/generate-command/__tests__/generate-command.test.js +301 -0
  34. package/frigg-cli/generate-command/azure-generator.js +43 -0
  35. package/frigg-cli/generate-command/gcp-generator.js +47 -0
  36. package/frigg-cli/generate-command/index.js +333 -0
  37. package/frigg-cli/generate-command/terraform-generator.js +555 -0
  38. package/frigg-cli/generate-iam-command.js +119 -0
  39. package/frigg-cli/index.js +189 -1
  40. package/frigg-cli/index.test.js +1 -4
  41. package/frigg-cli/init-command/backend-first-handler.js +756 -0
  42. package/frigg-cli/init-command/index.js +93 -0
  43. package/frigg-cli/init-command/template-handler.js +143 -0
  44. package/frigg-cli/install-command/index.js +1 -4
  45. package/frigg-cli/jest.config.js +124 -0
  46. package/frigg-cli/package.json +63 -0
  47. package/frigg-cli/repair-command/index.js +564 -0
  48. package/frigg-cli/ssm-command/index.js +308 -0
  49. package/frigg-cli/ssm-command/index.test.js +318 -0
  50. package/frigg-cli/start-command/index.js +118 -5
  51. package/frigg-cli/start-command/start-command.test.js +297 -0
  52. package/frigg-cli/test/init-command.test.js +180 -0
  53. package/frigg-cli/test/npm-registry.test.js +319 -0
  54. package/frigg-cli/ui-command/index.js +154 -0
  55. package/frigg-cli/utils/app-resolver.js +319 -0
  56. package/frigg-cli/utils/backend-path.js +16 -17
  57. package/frigg-cli/utils/database-validator.js +167 -0
  58. package/frigg-cli/utils/error-messages.js +329 -0
  59. package/frigg-cli/utils/npm-registry.js +167 -0
  60. package/frigg-cli/utils/process-manager.js +199 -0
  61. package/frigg-cli/utils/repo-detection.js +405 -0
  62. package/infrastructure/ARCHITECTURE.md +487 -0
  63. package/infrastructure/CLAUDE.md +481 -0
  64. package/infrastructure/HEALTH.md +468 -0
  65. package/infrastructure/README.md +540 -0
  66. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +391 -0
  67. package/infrastructure/__tests__/helpers/test-utils.js +275 -0
  68. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  69. package/infrastructure/__tests__/scoped-environment.test.js +126 -0
  70. package/infrastructure/__tests__/ssm-preload-node-options.test.js +79 -0
  71. package/infrastructure/__tests__/template-generation.test.js +687 -0
  72. package/infrastructure/create-frigg-infrastructure.js +129 -20
  73. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  74. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  75. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +105 -0
  76. package/infrastructure/docs/deployment-instructions.md +268 -0
  77. package/infrastructure/docs/generate-iam-command.md +278 -0
  78. package/infrastructure/docs/iam-policy-templates.md +193 -0
  79. package/infrastructure/domains/admin-scripts/admin-script-builder.js +567 -0
  80. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +1017 -0
  81. package/infrastructure/domains/admin-scripts/index.js +5 -0
  82. package/infrastructure/domains/database/aurora-builder.js +857 -0
  83. package/infrastructure/domains/database/aurora-builder.test.js +960 -0
  84. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  85. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  86. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  87. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  88. package/infrastructure/domains/database/migration-builder.js +757 -0
  89. package/infrastructure/domains/database/migration-builder.test.js +454 -0
  90. package/infrastructure/domains/database/migration-resolver.js +163 -0
  91. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  92. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  93. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  94. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  95. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  96. package/infrastructure/domains/health/application/ports/index.js +26 -0
  97. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  98. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  99. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  100. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  101. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  102. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  103. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  104. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  105. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  106. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  107. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  108. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  109. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  110. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  111. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  112. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  113. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  114. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  115. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  116. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  117. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  118. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  119. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  120. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  121. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  122. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  123. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  124. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  125. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  126. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  127. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  128. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  129. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  130. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  131. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  132. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  133. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  134. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  135. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  136. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  137. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  138. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  139. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  140. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  141. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  142. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  143. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  144. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  145. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  146. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  147. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  148. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  149. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  150. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  151. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  152. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  153. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  154. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  155. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  156. package/infrastructure/domains/integration/integration-builder.js +656 -0
  157. package/infrastructure/domains/integration/integration-builder.test.js +1064 -0
  158. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  159. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  160. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  161. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  162. package/infrastructure/domains/networking/vpc-builder.js +2101 -0
  163. package/infrastructure/domains/networking/vpc-builder.test.js +2001 -0
  164. package/infrastructure/domains/networking/vpc-discovery.js +184 -0
  165. package/infrastructure/domains/networking/vpc-discovery.test.js +368 -0
  166. package/infrastructure/domains/networking/vpc-resolver.js +514 -0
  167. package/infrastructure/domains/networking/vpc-resolver.test.js +841 -0
  168. package/infrastructure/domains/parameters/offload-utils.js +190 -0
  169. package/infrastructure/domains/parameters/offload-utils.test.js +193 -0
  170. package/infrastructure/domains/parameters/ssm-builder.js +132 -0
  171. package/infrastructure/domains/parameters/ssm-builder.test.js +346 -0
  172. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  173. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  174. package/infrastructure/domains/scheduler/scheduler-builder.js +247 -0
  175. package/infrastructure/domains/scheduler/scheduler-builder.test.js +118 -0
  176. package/infrastructure/domains/security/iam-generator.js +851 -0
  177. package/infrastructure/domains/security/iam-generator.test.js +287 -0
  178. package/infrastructure/domains/security/kms-builder.js +415 -0
  179. package/infrastructure/domains/security/kms-builder.test.js +392 -0
  180. package/infrastructure/domains/security/kms-discovery.js +80 -0
  181. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  182. package/infrastructure/domains/security/kms-resolver.js +96 -0
  183. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  184. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +418 -0
  185. package/infrastructure/domains/security/templates/iam-policy-basic.json +218 -0
  186. package/infrastructure/domains/security/templates/iam-policy-full.json +293 -0
  187. package/infrastructure/domains/shared/base-builder.js +112 -0
  188. package/infrastructure/domains/shared/base-resolver.js +186 -0
  189. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  190. package/infrastructure/domains/shared/builder-orchestrator.js +226 -0
  191. package/infrastructure/domains/shared/builder-orchestrator.test.js +258 -0
  192. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  193. package/infrastructure/domains/shared/cloudformation-discovery.js +681 -0
  194. package/infrastructure/domains/shared/cloudformation-discovery.test.js +1320 -0
  195. package/infrastructure/domains/shared/environment-builder.js +192 -0
  196. package/infrastructure/domains/shared/environment-builder.test.js +529 -0
  197. package/infrastructure/domains/shared/function-environments.js +97 -0
  198. package/infrastructure/domains/shared/function-environments.test.js +146 -0
  199. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +579 -0
  200. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +416 -0
  201. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  202. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  203. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  204. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  205. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  206. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  207. package/infrastructure/domains/shared/resource-discovery.js +256 -0
  208. package/infrastructure/domains/shared/resource-discovery.test.js +757 -0
  209. package/infrastructure/domains/shared/types/app-definition.js +225 -0
  210. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  211. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  212. package/infrastructure/domains/shared/types/index.js +46 -0
  213. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  214. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  215. package/infrastructure/domains/shared/utilities/base-definition-factory.js +409 -0
  216. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  217. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +319 -0
  218. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  219. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  220. package/infrastructure/domains/shared/utilities/nested-node-modules.js +53 -0
  221. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +61 -0
  222. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +159 -0
  223. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +444 -0
  224. package/infrastructure/domains/shared/validation/env-validator.js +78 -0
  225. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  226. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  227. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  228. package/infrastructure/esbuild.config.js +53 -0
  229. package/infrastructure/infrastructure-composer.js +168 -0
  230. package/infrastructure/infrastructure-composer.test.js +2042 -0
  231. package/infrastructure/integration.test.js +381 -0
  232. package/infrastructure/scripts/build-prisma-layer.js +701 -0
  233. package/infrastructure/scripts/build-prisma-layer.test.js +170 -0
  234. package/infrastructure/scripts/build-time-discovery.js +238 -0
  235. package/infrastructure/scripts/build-time-discovery.test.js +379 -0
  236. package/infrastructure/scripts/run-discovery.js +110 -0
  237. package/infrastructure/scripts/verify-prisma-layer.js +72 -0
  238. package/management-ui/README.md +203 -0
  239. package/package.json +48 -16
  240. package/test/index.js +2 -4
  241. package/test/mock-api.js +1 -3
  242. package/test/mock-integration.js +4 -14
  243. package/.eslintrc.json +0 -3
  244. package/CHANGELOG.md +0 -132
  245. package/infrastructure/serverless-template.js +0 -283
  246. package/infrastructure/webpack.config.js +0 -20
  247. package/test/auther-definition-tester.js +0 -125
@@ -0,0 +1,757 @@
1
+ /**
2
+ * Migration Infrastructure Builder
3
+ *
4
+ * Domain Layer - Hexagonal Architecture
5
+ *
6
+ * Responsible for:
7
+ * - SQS queue for migration jobs
8
+ * - Migration worker Lambda function (triggered by SQS)
9
+ * - Migration router Lambda function (HTTP API)
10
+ * - IAM permissions for SQS
11
+ *
12
+ * Only creates infrastructure when PostgreSQL is enabled.
13
+ * MongoDB uses `db push` which doesn't require migration queue/worker.
14
+ */
15
+
16
+ const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
17
+ const { isScopedEnvironmentActive } = require('../shared/function-environments');
18
+ const { nestedNodeModulesExcludes } = require('../shared/utilities/nested-node-modules');
19
+ const { MigrationResourceResolver } = require('./migration-resolver');
20
+ const { createEmptyDiscoveryResult, ResourceOwnership } = require('../shared/types');
21
+
22
+ class MigrationBuilder extends InfrastructureBuilder {
23
+ constructor() {
24
+ super();
25
+ this.name = 'MigrationBuilder';
26
+ }
27
+
28
+ shouldExecute(appDefinition) {
29
+ // Only create migration infrastructure for PostgreSQL
30
+ // MongoDB uses `db push` which doesn't need queue/worker
31
+ // Skip in local mode
32
+ if (process.env.FRIGG_SKIP_AWS_DISCOVERY === 'true') {
33
+ return false;
34
+ }
35
+
36
+ // Default to true if not explicitly disabled
37
+ return appDefinition.database?.postgres?.enable !== false;
38
+ }
39
+
40
+ getDependencies() {
41
+ return []; // No dependencies - migrations can run independently
42
+ }
43
+
44
+ validate(appDefinition) {
45
+ const result = new ValidationResult();
46
+
47
+ // No specific validation needed - PostgreSQL builder handles DB validation
48
+ // This builder just creates the migration infrastructure
49
+
50
+ return result;
51
+ }
52
+
53
+ /**
54
+ * Build migration infrastructure using ownership-based architecture
55
+ */
56
+ async build(appDefinition, discoveredResources) {
57
+ console.log(`\n[${this.name}] Configuring database migration infrastructure...`);
58
+
59
+ // Backwards compatibility: Translate old schema to new ownership schema
60
+ appDefinition = this.translateLegacyConfig(appDefinition, discoveredResources);
61
+
62
+ const usePrismaLayer = appDefinition.usePrismaLambdaLayer !== false;
63
+
64
+ const result = {
65
+ functions: {}, // Lambda function definitions
66
+ resources: {},
67
+ iamStatements: [],
68
+ environment: {},
69
+ };
70
+
71
+ // Get structured discovery result
72
+ const discovery = discoveredResources._structured || this.convertFlatDiscoveryToStructured(discoveredResources, appDefinition);
73
+
74
+ // Use MigrationResourceResolver to make ownership decisions
75
+ const resolver = new MigrationResourceResolver();
76
+ const decisions = resolver.resolveAll(appDefinition, discovery);
77
+
78
+ console.log('\n 📋 Resource Ownership Decisions:');
79
+ console.log(` Bucket: ${decisions.bucket.ownership} - ${decisions.bucket.reason}`);
80
+ console.log(` Queue: ${decisions.queue.ownership} - ${decisions.queue.reason}`);
81
+
82
+ // Build resources based on ownership decisions
83
+ await this.buildFromDecisions(decisions, appDefinition, discoveredResources, result, usePrismaLayer);
84
+
85
+ console.log(`[${this.name}] ✅ Migration infrastructure configuration completed`);
86
+ return result;
87
+ }
88
+
89
+ /**
90
+ * Convert flat discovery to structured discovery
91
+ * Provides backwards compatibility for tests
92
+ */
93
+ convertFlatDiscoveryToStructured(flatDiscovery, appDefinition = {}) {
94
+ const discovery = createEmptyDiscoveryResult();
95
+
96
+ if (!flatDiscovery) {
97
+ return discovery;
98
+ }
99
+
100
+ // Check if resources are from CloudFormation stack
101
+ const isManagedIsolated = appDefinition.managementMode === 'managed' &&
102
+ (appDefinition.vpcIsolation === 'isolated' || !appDefinition.vpcIsolation);
103
+ const hasExistingStackResources = isManagedIsolated &&
104
+ (flatDiscovery.migrationStatusBucket || flatDiscovery.migrationQueueUrl);
105
+
106
+ if (flatDiscovery.fromCloudFormationStack || hasExistingStackResources) {
107
+ discovery.fromCloudFormation = true;
108
+ discovery.stackName = flatDiscovery.stackName || 'assumed-stack';
109
+
110
+ // Add stack-managed resources
111
+ let existingLogicalIds = flatDiscovery.existingLogicalIds || [];
112
+
113
+ // Infer logical IDs from physical IDs if needed
114
+ if (hasExistingStackResources && existingLogicalIds.length === 0) {
115
+ if (flatDiscovery.migrationStatusBucket) existingLogicalIds.push('FriggMigrationStatusBucket');
116
+ if (flatDiscovery.migrationQueueUrl) existingLogicalIds.push('DbMigrationQueue');
117
+ }
118
+
119
+ existingLogicalIds.forEach(logicalId => {
120
+ let resourceType = '';
121
+ let physicalId = '';
122
+
123
+ if (logicalId === 'FriggMigrationStatusBucket') {
124
+ resourceType = 'AWS::S3::Bucket';
125
+ physicalId = flatDiscovery.migrationStatusBucket;
126
+ } else if (logicalId === 'DbMigrationQueue') {
127
+ resourceType = 'AWS::SQS::Queue';
128
+ physicalId = flatDiscovery.migrationQueueUrl;
129
+ }
130
+
131
+ if (physicalId && typeof physicalId === 'string') {
132
+ discovery.stackManaged.push({
133
+ logicalId,
134
+ physicalId,
135
+ resourceType
136
+ });
137
+ }
138
+ });
139
+ } else {
140
+ // Resources discovered from AWS API (external)
141
+ if (flatDiscovery.migrationStatusBucket && typeof flatDiscovery.migrationStatusBucket === 'string') {
142
+ discovery.external.push({
143
+ physicalId: flatDiscovery.migrationStatusBucket,
144
+ resourceType: 'AWS::S3::Bucket',
145
+ source: 'aws-discovery'
146
+ });
147
+ }
148
+
149
+ if (flatDiscovery.migrationQueueUrl && typeof flatDiscovery.migrationQueueUrl === 'string') {
150
+ discovery.external.push({
151
+ physicalId: flatDiscovery.migrationQueueUrl,
152
+ resourceType: 'AWS::SQS::Queue',
153
+ source: 'aws-discovery'
154
+ });
155
+ }
156
+ }
157
+
158
+ return discovery;
159
+ }
160
+
161
+ /**
162
+ * Translate legacy configuration to ownership-based configuration
163
+ * Provides backwards compatibility
164
+ */
165
+ translateLegacyConfig(appDefinition, discoveredResources) {
166
+ // If already using ownership schema, return as-is
167
+ if (appDefinition.migration?.ownership) {
168
+ return appDefinition;
169
+ }
170
+
171
+ const translated = JSON.parse(JSON.stringify(appDefinition));
172
+
173
+ // Initialize ownership sections
174
+ if (!translated.migration) translated.migration = {};
175
+ if (!translated.migration.ownership) {
176
+ translated.migration.ownership = {};
177
+ }
178
+
179
+ // Handle top-level managementMode
180
+ const globalMode = appDefinition.managementMode || 'discover';
181
+ const vpcIsolation = appDefinition.vpcIsolation || 'shared';
182
+
183
+ if (globalMode === 'managed') {
184
+ if (vpcIsolation === 'isolated') {
185
+ const hasStackResources = discoveredResources?.migrationStatusBucket ||
186
+ discoveredResources?.migrationQueueUrl;
187
+
188
+ if (hasStackResources) {
189
+ translated.migration.ownership.bucket = 'auto';
190
+ translated.migration.ownership.queue = 'auto';
191
+ console.log(` managementMode='managed' + vpcIsolation='isolated' → stack has migration resources, reusing`);
192
+ } else {
193
+ translated.migration.ownership.bucket = 'stack';
194
+ translated.migration.ownership.queue = 'stack';
195
+ console.log(` managementMode='managed' + vpcIsolation='isolated' → no stack migration resources, creating new`);
196
+ }
197
+ } else {
198
+ translated.migration.ownership.bucket = 'auto';
199
+ translated.migration.ownership.queue = 'auto';
200
+ console.log(` managementMode='managed' + vpcIsolation='shared' → discovering migration resources`);
201
+ }
202
+ } else {
203
+ // Default to creating resources (current behavior)
204
+ translated.migration.ownership.bucket = 'stack';
205
+ translated.migration.ownership.queue = 'stack';
206
+ }
207
+
208
+ return translated;
209
+ }
210
+
211
+ /**
212
+ * Build migration resources based on ownership decisions
213
+ */
214
+ async buildFromDecisions(decisions, appDefinition, discoveredResources, result, usePrismaLayer = true) {
215
+ // Determine if we need to create resources or use existing ones
216
+ const shouldCreateBucket = decisions.bucket.ownership === ResourceOwnership.STACK;
217
+ const shouldCreateQueue = decisions.queue.ownership === ResourceOwnership.STACK;
218
+
219
+ if (shouldCreateBucket && shouldCreateQueue && !decisions.bucket.physicalId && !decisions.queue.physicalId) {
220
+ // Create all new migration infrastructure
221
+ console.log(' → Creating new migration infrastructure in stack');
222
+ await this.createMigrationInfrastructure(appDefinition, result, usePrismaLayer);
223
+ } else if ((decisions.bucket.ownership === ResourceOwnership.STACK && decisions.bucket.physicalId) ||
224
+ (decisions.queue.ownership === ResourceOwnership.STACK && decisions.queue.physicalId)) {
225
+ // Resources exist in stack - add definitions (CloudFormation idempotency)
226
+ console.log(' → Adding migration definitions to template (existing in stack)');
227
+ await this.createMigrationInfrastructure(appDefinition, result, usePrismaLayer);
228
+ } else {
229
+ // Use external resources
230
+ console.log(' → Using external migration resources');
231
+ await this.useExternalMigrationResources(decisions, appDefinition, result, usePrismaLayer);
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Create Lambda function definitions for database migrations
237
+ * Based on refactor/add-better-support-for-commands branch implementation
238
+ */
239
+ async createFunctionDefinitions(result, usePrismaLayer = true, appDefinition = {}) {
240
+ console.log(' 🔍 DEBUG: createFunctionDefinitions called');
241
+ console.log(' 🔍 DEBUG: result.functions is:', typeof result.functions, result.functions);
242
+ // Migration WORKER package config (needs Prisma CLI WASM files)
243
+ const migrationWorkerPackageConfig = {
244
+ individually: true,
245
+ exclude: [
246
+ // Exclude Prisma runtime client when using Lambda Layer (but keep CLI folder)
247
+ ...(usePrismaLayer ? [
248
+ 'node_modules/@prisma/client/**',
249
+ 'node_modules/.prisma/**',
250
+ 'node_modules/@friggframework/core/generated/**',
251
+ ] : []),
252
+ // But KEEP node_modules/prisma/** (the CLI with WASM)
253
+
254
+ ...nestedNodeModulesExcludes(appDefinition, usePrismaLayer),
255
+
256
+ // Exclude AWS SDK (provided by Lambda runtime)
257
+ 'node_modules/aws-sdk/**',
258
+ 'node_modules/@aws-sdk/**',
259
+
260
+ // Exclude build tools
261
+ 'node_modules/esbuild/**',
262
+ 'node_modules/@esbuild/**',
263
+ 'node_modules/typescript/**',
264
+ 'node_modules/webpack/**',
265
+ 'node_modules/osls/**',
266
+ 'node_modules/serverless-esbuild/**',
267
+ 'node_modules/serverless-jetpack/**',
268
+ 'node_modules/serverless-offline/**',
269
+ 'node_modules/serverless-offline-sqs/**',
270
+ 'node_modules/serverless-dotenv-plugin/**',
271
+ 'node_modules/serverless-kms-grants/**',
272
+
273
+ // Exclude dev dependencies
274
+ 'node_modules/@friggframework/test/**',
275
+ 'node_modules/@friggframework/eslint-config/**',
276
+ 'node_modules/@friggframework/prettier-config/**',
277
+ 'node_modules/@friggframework/devtools/**',
278
+ 'node_modules/@friggframework/serverless-plugin/**',
279
+ 'node_modules/jest/**',
280
+ 'node_modules/prettier/**',
281
+ 'node_modules/eslint/**',
282
+
283
+ // Exclude non-essential Frigg core modules
284
+ 'node_modules/@friggframework/core/generated/prisma-mongodb/**',
285
+ 'node_modules/@friggframework/core/integrations/**',
286
+ 'node_modules/@friggframework/core/user/**',
287
+
288
+ // Exclude other handlers we don't need (keep db-migration worker)
289
+ 'node_modules/@friggframework/core/handlers/routers/auth.js',
290
+ 'node_modules/@friggframework/core/handlers/routers/health.js',
291
+ 'node_modules/@friggframework/core/handlers/routers/user.js',
292
+ 'node_modules/@friggframework/core/handlers/routers/websocket.js',
293
+ 'node_modules/@friggframework/core/handlers/routers/integration-*.js',
294
+ 'node_modules/@friggframework/core/handlers/workers/integration-*.js',
295
+
296
+ // Exclude wrong OS binaries
297
+ '**/query-engine-darwin*',
298
+ '**/schema-engine-darwin*',
299
+ '**/libquery_engine-darwin*',
300
+ '**/*-darwin-arm64*',
301
+ '**/*-darwin*',
302
+
303
+ // Migration worker DOES need Prisma CLI WASM files (for migrate deploy)
304
+ // Only exclude runtime engine WASM (query engine internals)
305
+ '**/runtime/*.wasm',
306
+
307
+ // Additional size optimizations
308
+ '**/*.map',
309
+ '**/*.md',
310
+ '**/LICENSE*',
311
+ '**/*.d.ts',
312
+ '**/*.d.mts',
313
+ '**/examples/**',
314
+ '**/docs/**',
315
+ 'src/**',
316
+ 'test/**',
317
+ 'layers/**',
318
+ 'coverage/**',
319
+ 'deploy.log',
320
+ '.env.backup',
321
+ 'docker-compose.yml',
322
+ 'jest.config.js',
323
+ 'jest.unit.config.js',
324
+ 'package-lock.json',
325
+ '**/*.test.js',
326
+ '**/*.spec.js',
327
+ '**/.claude-flow/**',
328
+ '**/.swarm/**',
329
+ ],
330
+ };
331
+
332
+ // Migration ROUTER package config (lighter, no Prisma CLI needed)
333
+ const migrationRouterPackageConfig = {
334
+ individually: true,
335
+ exclude: [
336
+ // Exclude Prisma runtime client when using Lambda Layer
337
+ ...(usePrismaLayer ? [
338
+ 'node_modules/@prisma/client/**',
339
+ 'node_modules/.prisma/**',
340
+ 'node_modules/@friggframework/core/generated/**',
341
+ ] : []),
342
+
343
+ // Router only skips Prisma CLI if Lambda Layer is enabled
344
+ ...(usePrismaLayer ? ['node_modules/prisma/**'] : []),
345
+
346
+ ...nestedNodeModulesExcludes(appDefinition, usePrismaLayer),
347
+
348
+ // Exclude AWS SDK (provided by Lambda runtime)
349
+ 'node_modules/aws-sdk/**',
350
+ 'node_modules/@aws-sdk/**',
351
+
352
+ // Exclude build tools
353
+ 'node_modules/esbuild/**',
354
+ 'node_modules/@esbuild/**',
355
+ 'node_modules/typescript/**',
356
+ 'node_modules/webpack/**',
357
+ 'node_modules/osls/**',
358
+ 'node_modules/serverless-esbuild/**',
359
+ 'node_modules/serverless-jetpack/**',
360
+ 'node_modules/serverless-offline/**',
361
+ 'node_modules/serverless-offline-sqs/**',
362
+ 'node_modules/serverless-dotenv-plugin/**',
363
+ 'node_modules/serverless-kms-grants/**',
364
+
365
+ // Exclude dev dependencies
366
+ 'node_modules/@friggframework/test/**',
367
+ 'node_modules/@friggframework/eslint-config/**',
368
+ 'node_modules/@friggframework/prettier-config/**',
369
+ 'node_modules/@friggframework/devtools/**',
370
+ 'node_modules/@friggframework/serverless-plugin/**',
371
+ 'node_modules/jest/**',
372
+ 'node_modules/prettier/**',
373
+ 'node_modules/eslint/**',
374
+
375
+ // Exclude non-essential Frigg core modules
376
+ 'node_modules/@friggframework/core/generated/prisma-mongodb/**',
377
+ 'node_modules/@friggframework/core/integrations/**',
378
+ 'node_modules/@friggframework/core/user/**',
379
+
380
+ // Exclude other handlers we don't need (keep db-migration router)
381
+ 'node_modules/@friggframework/core/handlers/routers/auth.js',
382
+ 'node_modules/@friggframework/core/handlers/routers/health.js',
383
+ 'node_modules/@friggframework/core/handlers/routers/user.js',
384
+ 'node_modules/@friggframework/core/handlers/routers/websocket.js',
385
+ 'node_modules/@friggframework/core/handlers/routers/integration-*.js',
386
+ 'node_modules/@friggframework/core/handlers/workers/**',
387
+
388
+ // Exclude wrong OS binaries
389
+ '**/query-engine-darwin*',
390
+ '**/schema-engine-darwin*',
391
+ '**/libquery_engine-darwin*',
392
+ '**/*-darwin-arm64*',
393
+ '**/*-darwin*',
394
+
395
+ // Router doesn't run migrations - exclude ALL WASM files
396
+ '**/runtime/*.wasm',
397
+ '**/*.wasm*',
398
+
399
+ // Additional size optimizations
400
+ '**/*.map',
401
+ '**/*.md',
402
+ '**/LICENSE*',
403
+ '**/*.d.ts',
404
+ '**/*.d.mts',
405
+ '**/test/**',
406
+ '**/tests/**',
407
+ '**/__tests__/**',
408
+ '**/examples/**',
409
+ '**/docs/**',
410
+ 'src/**',
411
+ 'test/**',
412
+ 'layers/**',
413
+ 'coverage/**',
414
+ 'deploy.log',
415
+ '.env.backup',
416
+ 'docker-compose.yml',
417
+ 'jest.config.js',
418
+ 'jest.unit.config.js',
419
+ 'package-lock.json',
420
+ '**/*.test.js',
421
+ '**/*.spec.js',
422
+ '**/.claude-flow/**',
423
+ '**/.swarm/**',
424
+ ],
425
+ };
426
+
427
+ // Create migration worker Lambda (triggered by SQS)
428
+ console.log(' 🔍 DEBUG: About to create dbMigrationWorker...');
429
+ result.functions.dbMigrationWorker = {
430
+ handler: 'node_modules/@friggframework/core/handlers/workers/db-migration.handler',
431
+ ...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }),
432
+ skipEsbuild: true,
433
+ timeout: 900, // 15 minutes for long migrations
434
+ memorySize: 1024, // Extra memory for Prisma operations
435
+ reservedConcurrency: 1, // Process one migration at a time (critical for safety)
436
+ description: 'Database migration worker (triggered by SQS queue)',
437
+ package: migrationWorkerPackageConfig,
438
+ environment: {
439
+ // Ensure migration functions get DATABASE_URL from provider.environment
440
+ // Note: Serverless will merge this with provider.environment
441
+ },
442
+ events: [
443
+ {
444
+ sqs: {
445
+ arn: { 'Fn::GetAtt': ['DbMigrationQueue', 'Arn'] },
446
+ batchSize: 1, // Process one migration at a time
447
+ },
448
+ },
449
+ ],
450
+ };
451
+ console.log(' ✓ Created dbMigrationWorker function');
452
+ console.log(' 🔍 DEBUG: result.functions.dbMigrationWorker is:', !!result.functions.dbMigrationWorker);
453
+
454
+ // Create migration router Lambda (HTTP API)
455
+ console.log(' 🔍 DEBUG: About to create dbMigrationRouter...');
456
+ result.functions.dbMigrationRouter = {
457
+ handler: 'node_modules/@friggframework/core/handlers/routers/db-migration.handler',
458
+ // No Prisma layer needed - router doesn't access database
459
+ skipEsbuild: true,
460
+ timeout: 30, // Router just queues jobs, doesn't run migrations
461
+ memorySize: 512,
462
+ description: 'Database migration HTTP API (POST to trigger, GET to check status)',
463
+ package: migrationRouterPackageConfig,
464
+ environment: {
465
+ // Ensure migration functions get DATABASE_URL from provider.environment
466
+ // Note: Serverless will merge this with provider.environment
467
+ },
468
+ events: [
469
+ // Paths must match the Express router in core's db-migration.js,
470
+ // which mounts under /admin/db-migrate (consolidated with the
471
+ // other admin endpoints). A mismatch routes API Gateway to the
472
+ // Lambda but Express 404s ("Cannot POST /db-migrate").
473
+ {
474
+ httpApi: {
475
+ path: '/admin/db-migrate/status',
476
+ method: 'GET',
477
+ },
478
+ },
479
+ { httpApi: { path: '/admin/db-migrate', method: 'POST' } },
480
+ {
481
+ httpApi: {
482
+ path: '/admin/db-migrate/resolve',
483
+ method: 'POST',
484
+ },
485
+ },
486
+ {
487
+ httpApi: {
488
+ path: '/admin/db-migrate/{processId}',
489
+ method: 'GET',
490
+ },
491
+ },
492
+ ],
493
+ };
494
+ console.log(' ✓ Created dbMigrationRouter function');
495
+
496
+ // Add worker function name to router environment (for Lambda invocation)
497
+ // Router needs this to invoke worker for database state checks
498
+ if (!result.functions.dbMigrationRouter.environment) {
499
+ result.functions.dbMigrationRouter.environment = {};
500
+ }
501
+ result.functions.dbMigrationRouter.environment.WORKER_FUNCTION_NAME = {
502
+ Ref: 'DbMigrationWorkerLambdaFunction',
503
+ };
504
+ console.log(' ✓ Added WORKER_FUNCTION_NAME environment variable to router');
505
+ console.log(' 🔍 DEBUG: result.functions keys:', Object.keys(result.functions));
506
+ console.log(' 🔍 DEBUG: Exiting createFunctionDefinitions');
507
+ }
508
+
509
+ /**
510
+ * Create migration infrastructure CloudFormation resources
511
+ * Creates S3 bucket, SQS queue, and Lambda function definitions
512
+ */
513
+ async createMigrationInfrastructure(appDefinition, result, usePrismaLayer = true) {
514
+ console.log(' 🔍 DEBUG: createMigrationInfrastructure called');
515
+ console.log(' 🔍 DEBUG: result object before createFunctionDefinitions:', Object.keys(result));
516
+
517
+ // Create Lambda function definitions first (they reference the queue)
518
+ await this.createFunctionDefinitions(result, usePrismaLayer, appDefinition);
519
+
520
+ console.log(' 🔍 DEBUG: result.functions after createFunctionDefinitions:', Object.keys(result.functions || {}));
521
+
522
+ // Create S3 bucket for migration status tracking
523
+ result.resources.FriggMigrationStatusBucket = {
524
+ Type: 'AWS::S3::Bucket',
525
+ DeletionPolicy: 'Retain', // Protect migration history during stack rollbacks/deletions
526
+ UpdateReplacePolicy: 'Retain', // Protect during stack updates that require replacement
527
+ Properties: {
528
+ // Let CloudFormation auto-generate bucket name for global uniqueness
529
+ // Result: ${StackName}-friggmigrationstatusbucket-${randomHash}
530
+ // Example: quo-integrations-prod-friggmigrationstatusbucket-abc123xyz
531
+ // This ensures no conflicts across accounts/regions/stages
532
+ // BucketName: undefined (CloudFormation generates unique name)
533
+ VersioningConfiguration: {
534
+ Status: 'Enabled', // Enable versioning for audit trail
535
+ },
536
+ LifecycleConfiguration: {
537
+ Rules: [
538
+ {
539
+ Id: 'DeleteOldMigrations',
540
+ Status: 'Enabled',
541
+ ExpirationInDays: 90, // Keep migration history for 90 days
542
+ },
543
+ ],
544
+ },
545
+ PublicAccessBlockConfiguration: {
546
+ BlockPublicAcls: true,
547
+ BlockPublicPolicy: true,
548
+ IgnorePublicAcls: true,
549
+ RestrictPublicBuckets: true,
550
+ },
551
+ Tags: [
552
+ { Key: 'ManagedBy', Value: 'Frigg' },
553
+ { Key: 'Purpose', Value: 'MigrationStatusTracking' },
554
+ ],
555
+ },
556
+ };
557
+
558
+ console.log(' ✓ Created FriggMigrationStatusBucket resource');
559
+
560
+ // Create SQS queue for migration jobs
561
+ result.resources.DbMigrationQueue = {
562
+ Type: 'AWS::SQS::Queue',
563
+ Properties: {
564
+ QueueName: '${self:service}-${self:provider.stage}-DbMigrationQueue',
565
+ VisibilityTimeout: 900, // 15 minutes for long-running migrations
566
+ MessageRetentionPeriod: 1209600, // 14 days
567
+ ReceiveMessageWaitTimeSeconds: 20, // Long polling
568
+ },
569
+ };
570
+
571
+ console.log(' ✓ Created DbMigrationQueue resource');
572
+
573
+ const migrationEnvironment = {
574
+ // S3 bucket for migration Lambda functions
575
+ S3_BUCKET_NAME: { Ref: 'FriggMigrationStatusBucket' },
576
+ MIGRATION_STATUS_BUCKET: { Ref: 'FriggMigrationStatusBucket' },
577
+ DB_MIGRATION_QUEUE_URL: { Ref: 'DbMigrationQueue' },
578
+ };
579
+
580
+ if (isScopedEnvironmentActive(appDefinition)) {
581
+ // Only the migration functions read these
582
+ result.functionEnvironments = result.functionEnvironments || {};
583
+ for (const fnName of ['dbMigrationRouter', 'dbMigrationWorker']) {
584
+ result.functionEnvironments[fnName] = {
585
+ ...result.functionEnvironments[fnName],
586
+ ...migrationEnvironment,
587
+ };
588
+ }
589
+ } else {
590
+ Object.assign(result.environment, migrationEnvironment);
591
+ }
592
+
593
+ // Hardcode DB_TYPE for PostgreSQL-only migrations. Stays app-wide
594
+ // even when scoping: it is tiny and broadly consumed, and scoping it
595
+ // would push every function through the app-definition fallback in
596
+ // core's getDatabaseType() at cold start.
597
+ result.environment.DB_TYPE = 'postgresql';
598
+
599
+ console.log(' ✓ Added S3_BUCKET_NAME, DB_MIGRATION_QUEUE_URL, and DB_TYPE environment variables');
600
+
601
+ // Add IAM permissions for SQS (for Lambda functions)
602
+ result.iamStatements.push({
603
+ Effect: 'Allow',
604
+ Action: [
605
+ 'sqs:SendMessage',
606
+ 'sqs:GetQueueUrl',
607
+ 'sqs:GetQueueAttributes',
608
+ ],
609
+ Resource: { 'Fn::GetAtt': ['DbMigrationQueue', 'Arn'] },
610
+ });
611
+
612
+ console.log(' ✓ Added SQS IAM permissions');
613
+
614
+ // Add IAM permissions for S3 (migration status storage)
615
+ // Object-level permissions (put, get, delete)
616
+ result.iamStatements.push({
617
+ Effect: 'Allow',
618
+ Action: [
619
+ 's3:PutObject',
620
+ 's3:GetObject',
621
+ 's3:DeleteObject',
622
+ ],
623
+ Resource: {
624
+ 'Fn::Join': [
625
+ '',
626
+ [
627
+ { 'Fn::GetAtt': ['FriggMigrationStatusBucket', 'Arn'] },
628
+ '/migrations/*',
629
+ ],
630
+ ],
631
+ },
632
+ });
633
+
634
+ // Bucket-level permissions (list objects)
635
+ result.iamStatements.push({
636
+ Effect: 'Allow',
637
+ Action: ['s3:ListBucket'],
638
+ Resource: { 'Fn::GetAtt': ['FriggMigrationStatusBucket', 'Arn'] },
639
+ });
640
+
641
+ console.log(' ✓ Added S3 IAM permissions for migration status tracking');
642
+
643
+ // Add IAM permission for router to invoke worker Lambda
644
+ result.iamStatements.push({
645
+ Effect: 'Allow',
646
+ Action: ['lambda:InvokeFunction'],
647
+ Resource: {
648
+ 'Fn::Sub': 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-dbMigrationWorker',
649
+ },
650
+ });
651
+
652
+ console.log(' ✓ Added Lambda invocation permissions for router → worker');
653
+ }
654
+
655
+ /**
656
+ * Use external migration resources (S3 bucket and SQS queue)
657
+ * Only references external resources - Lambda functions are defined in serverless.yml
658
+ */
659
+ async useExternalMigrationResources(decisions, appDefinition, result, usePrismaLayer = true) {
660
+ // Reference external bucket
661
+ const bucketName = decisions.bucket.physicalId;
662
+ if (!bucketName) {
663
+ throw new Error('External bucket specified but no migrationStatusBucket discovered');
664
+ }
665
+
666
+ // Reference external queue
667
+ const queueUrl = decisions.queue.physicalId;
668
+ if (!queueUrl) {
669
+ throw new Error('External queue specified but no migrationQueueUrl discovered');
670
+ }
671
+
672
+ console.log(` ✓ Using external S3 bucket: ${bucketName}`);
673
+ console.log(` ✓ Using external SQS queue: ${queueUrl}`);
674
+
675
+ // Extract queue ARN from queue URL for IAM permissions
676
+ const queueArn = queueUrl.replace('https://sqs.', 'arn:aws:sqs:')
677
+ .replace('.amazonaws.com/', ':')
678
+ .replace(/\//g, ':');
679
+
680
+ // Add environment variables (using external resource names/URLs)
681
+ const migrationEnvironment = {
682
+ S3_BUCKET_NAME: bucketName,
683
+ MIGRATION_STATUS_BUCKET: bucketName,
684
+ DB_MIGRATION_QUEUE_URL: queueUrl,
685
+ };
686
+
687
+ if (isScopedEnvironmentActive(appDefinition)) {
688
+ // Only the migration functions read these
689
+ result.functionEnvironments = result.functionEnvironments || {};
690
+ for (const fnName of ['dbMigrationRouter', 'dbMigrationWorker']) {
691
+ result.functionEnvironments[fnName] = {
692
+ ...result.functionEnvironments[fnName],
693
+ ...migrationEnvironment,
694
+ };
695
+ }
696
+ } else {
697
+ Object.assign(result.environment, migrationEnvironment);
698
+ }
699
+
700
+ // Hardcode DB_TYPE for PostgreSQL-only migrations. Stays app-wide
701
+ // even when scoping: it is tiny and broadly consumed, and scoping it
702
+ // would push every function through the app-definition fallback in
703
+ // core's getDatabaseType() at cold start.
704
+ result.environment.DB_TYPE = 'postgresql';
705
+
706
+ console.log(' ✓ Added S3_BUCKET_NAME, DB_MIGRATION_QUEUE_URL, and DB_TYPE environment variables');
707
+
708
+ // Add IAM permissions for external SQS queue
709
+ result.iamStatements.push({
710
+ Effect: 'Allow',
711
+ Action: [
712
+ 'sqs:SendMessage',
713
+ 'sqs:GetQueueUrl',
714
+ 'sqs:GetQueueAttributes',
715
+ ],
716
+ Resource: queueArn,
717
+ });
718
+
719
+ console.log(' ✓ Added SQS IAM permissions');
720
+
721
+ // Add IAM permissions for external S3 bucket
722
+ const bucketArn = `arn:aws:s3:::${bucketName}`;
723
+ result.iamStatements.push({
724
+ Effect: 'Allow',
725
+ Action: [
726
+ 's3:PutObject',
727
+ 's3:GetObject',
728
+ 's3:DeleteObject',
729
+ ],
730
+ Resource: `${bucketArn}/migrations/*`,
731
+ });
732
+
733
+ result.iamStatements.push({
734
+ Effect: 'Allow',
735
+ Action: ['s3:ListBucket'],
736
+ Resource: bucketArn,
737
+ });
738
+
739
+ console.log(' ✓ Added S3 IAM permissions for migration status tracking');
740
+
741
+ // Add IAM permission for router to invoke worker Lambda
742
+ result.iamStatements.push({
743
+ Effect: 'Allow',
744
+ Action: ['lambda:InvokeFunction'],
745
+ Resource: {
746
+ 'Fn::Sub': 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-dbMigrationWorker',
747
+ },
748
+ });
749
+
750
+ console.log(' ✓ Added Lambda invocation permissions for router → worker');
751
+ }
752
+ }
753
+
754
+ module.exports = {
755
+ MigrationBuilder,
756
+ };
757
+