@friggframework/devtools 2.0.0-next.62 → 2.0.0-next.63

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 (165) hide show
  1. package/infrastructure/ARCHITECTURE.md +487 -0
  2. package/infrastructure/CLAUDE.md +481 -0
  3. package/infrastructure/HEALTH.md +468 -0
  4. package/infrastructure/README.md +522 -0
  5. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +391 -0
  6. package/infrastructure/__tests__/helpers/test-utils.js +277 -0
  7. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  8. package/infrastructure/__tests__/template-generation.test.js +687 -0
  9. package/infrastructure/create-frigg-infrastructure.js +147 -0
  10. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  11. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  12. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +105 -0
  13. package/infrastructure/docs/deployment-instructions.md +268 -0
  14. package/infrastructure/docs/generate-iam-command.md +278 -0
  15. package/infrastructure/docs/iam-policy-templates.md +193 -0
  16. package/infrastructure/domains/database/aurora-builder.js +809 -0
  17. package/infrastructure/domains/database/aurora-builder.test.js +950 -0
  18. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  19. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  20. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  21. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  22. package/infrastructure/domains/database/migration-builder.js +701 -0
  23. package/infrastructure/domains/database/migration-builder.test.js +321 -0
  24. package/infrastructure/domains/database/migration-resolver.js +163 -0
  25. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  26. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  27. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  28. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  29. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  30. package/infrastructure/domains/health/application/ports/index.js +26 -0
  31. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  32. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  33. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  34. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  35. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  36. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  37. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  38. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  39. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  40. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  41. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  42. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  43. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  44. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  45. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  46. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  47. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  48. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  49. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  50. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  51. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  52. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  53. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  54. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  55. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  56. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  57. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  58. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  59. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  60. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  61. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  62. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  63. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  64. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  65. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  66. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  67. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  68. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  69. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  70. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  71. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  72. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  73. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  74. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  75. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  76. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  77. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  78. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  79. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  80. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  81. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  82. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  83. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  84. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  85. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  86. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  87. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  88. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  89. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  90. package/infrastructure/domains/integration/integration-builder.js +404 -0
  91. package/infrastructure/domains/integration/integration-builder.test.js +690 -0
  92. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  93. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  94. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  95. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  96. package/infrastructure/domains/networking/vpc-builder.js +2051 -0
  97. package/infrastructure/domains/networking/vpc-builder.test.js +1960 -0
  98. package/infrastructure/domains/networking/vpc-discovery.js +177 -0
  99. package/infrastructure/domains/networking/vpc-discovery.test.js +350 -0
  100. package/infrastructure/domains/networking/vpc-resolver.js +505 -0
  101. package/infrastructure/domains/networking/vpc-resolver.test.js +801 -0
  102. package/infrastructure/domains/parameters/ssm-builder.js +79 -0
  103. package/infrastructure/domains/parameters/ssm-builder.test.js +189 -0
  104. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  105. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  106. package/infrastructure/domains/security/iam-generator.js +816 -0
  107. package/infrastructure/domains/security/iam-generator.test.js +204 -0
  108. package/infrastructure/domains/security/kms-builder.js +415 -0
  109. package/infrastructure/domains/security/kms-builder.test.js +392 -0
  110. package/infrastructure/domains/security/kms-discovery.js +80 -0
  111. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  112. package/infrastructure/domains/security/kms-resolver.js +96 -0
  113. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  114. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +401 -0
  115. package/infrastructure/domains/security/templates/iam-policy-basic.json +218 -0
  116. package/infrastructure/domains/security/templates/iam-policy-full.json +288 -0
  117. package/infrastructure/domains/shared/base-builder.js +112 -0
  118. package/infrastructure/domains/shared/base-resolver.js +186 -0
  119. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  120. package/infrastructure/domains/shared/builder-orchestrator.js +212 -0
  121. package/infrastructure/domains/shared/builder-orchestrator.test.js +213 -0
  122. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  123. package/infrastructure/domains/shared/cloudformation-discovery.js +672 -0
  124. package/infrastructure/domains/shared/cloudformation-discovery.test.js +985 -0
  125. package/infrastructure/domains/shared/environment-builder.js +119 -0
  126. package/infrastructure/domains/shared/environment-builder.test.js +247 -0
  127. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +579 -0
  128. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +416 -0
  129. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  130. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  131. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  132. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  133. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  134. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  135. package/infrastructure/domains/shared/resource-discovery.js +233 -0
  136. package/infrastructure/domains/shared/resource-discovery.test.js +588 -0
  137. package/infrastructure/domains/shared/types/app-definition.js +205 -0
  138. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  139. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  140. package/infrastructure/domains/shared/types/index.js +46 -0
  141. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  142. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  143. package/infrastructure/domains/shared/utilities/base-definition-factory.js +408 -0
  144. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  145. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +291 -0
  146. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  147. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  148. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +159 -0
  149. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +444 -0
  150. package/infrastructure/domains/shared/validation/env-validator.js +78 -0
  151. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  152. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  153. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  154. package/infrastructure/esbuild.config.js +53 -0
  155. package/infrastructure/index.js +4 -0
  156. package/infrastructure/infrastructure-composer.js +117 -0
  157. package/infrastructure/infrastructure-composer.test.js +1895 -0
  158. package/infrastructure/integration.test.js +383 -0
  159. package/infrastructure/scripts/build-prisma-layer.js +701 -0
  160. package/infrastructure/scripts/build-prisma-layer.test.js +170 -0
  161. package/infrastructure/scripts/build-time-discovery.js +238 -0
  162. package/infrastructure/scripts/build-time-discovery.test.js +379 -0
  163. package/infrastructure/scripts/run-discovery.js +110 -0
  164. package/infrastructure/scripts/verify-prisma-layer.js +72 -0
  165. package/package.json +8 -7
@@ -0,0 +1,701 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Build Prisma Lambda Layer
5
+ *
6
+ * Creates a MINIMAL Lambda Layer containing only Prisma runtime client and query engines.
7
+ * This reduces individual Lambda function sizes by ~60% (120MB → 45MB).
8
+ *
9
+ * IMPORTANT: This layer does NOT include the Prisma CLI (saves ~82MB).
10
+ * The CLI is only needed for migrations and is packaged separately with the dbMigrate function.
11
+ *
12
+ * The layer is configured based on AppDefinition database settings:
13
+ * - PostgreSQL: Includes PostgreSQL client + query engine + migrations
14
+ * - MongoDB: Includes MongoDB client + query engine + migrations (if needed)
15
+ * - Defaults to PostgreSQL only if not specified
16
+ *
17
+ * Usage:
18
+ * node scripts/build-prisma-layer.js
19
+ * npm run build:prisma-layer
20
+ *
21
+ * Output:
22
+ * layers/prisma/nodejs/node_modules/
23
+ * ├── @prisma/client (runtime only, ~10-15MB)
24
+ * ├── generated/prisma-postgresql (if PostgreSQL enabled)
25
+ * │ ├── schema.prisma
26
+ * │ └── migrations/
27
+ * └── generated/prisma-mongodb (if MongoDB enabled)
28
+ * ├── schema.prisma
29
+ * └── migrations/
30
+ *
31
+ * See: LAMBDA-LAYER-PRISMA.md for complete documentation
32
+ */
33
+
34
+ const fs = require('fs-extra');
35
+ const path = require('path');
36
+ const { execSync } = require('child_process');
37
+
38
+ /**
39
+ * Find @friggframework/core package, handling workspace hoisting
40
+ * Searches up the directory tree to find node_modules/@friggframework/core
41
+ */
42
+ function findCorePackage(startDir) {
43
+ let currentDir = startDir;
44
+ const root = path.parse(currentDir).root;
45
+
46
+ while (currentDir !== root) {
47
+ const candidatePath = path.join(
48
+ currentDir,
49
+ 'node_modules/@friggframework/core'
50
+ );
51
+ if (fs.existsSync(candidatePath)) {
52
+ return candidatePath;
53
+ }
54
+ currentDir = path.dirname(currentDir);
55
+ }
56
+
57
+ throw new Error(
58
+ '@friggframework/core not found in node_modules.\n' +
59
+ 'Run "npm install" to install dependencies.'
60
+ );
61
+ }
62
+
63
+ /**
64
+ * Determine which database clients to include based on configuration
65
+ * @param {Object} databaseConfig - Database configuration from AppDefinition
66
+ * @returns {Array} List of generated client packages to include
67
+ */
68
+ function getGeneratedClientPackages(databaseConfig = {}) {
69
+ const packages = [];
70
+
71
+ // Check if MongoDB is enabled (via mongoDB or documentDB config)
72
+ const mongoEnabled =
73
+ databaseConfig?.mongoDB?.enable === true ||
74
+ databaseConfig?.documentDB?.enable === true;
75
+ if (mongoEnabled) {
76
+ packages.push('generated/prisma-mongodb');
77
+ log('Including MongoDB client (based on AppDefinition)', 'blue');
78
+ }
79
+
80
+ // Check if PostgreSQL is enabled (default to true if not specified)
81
+ const postgresEnabled = databaseConfig?.postgres?.enable !== false;
82
+ if (postgresEnabled) {
83
+ packages.push('generated/prisma-postgresql');
84
+ log('Including PostgreSQL client (based on AppDefinition)', 'blue');
85
+ }
86
+
87
+ // If neither specified, default to PostgreSQL only
88
+ if (packages.length === 0) {
89
+ packages.push('generated/prisma-postgresql');
90
+ log('No database specified - defaulting to PostgreSQL', 'yellow');
91
+ }
92
+
93
+ return packages;
94
+ }
95
+
96
+ function getMigrationsPackages(clientPackages) {
97
+ return clientPackages.map((pkg) => ({
98
+ dbType: pkg.replace('generated/prisma-', ''),
99
+ clientPackage: pkg,
100
+ }));
101
+ }
102
+
103
+ function getMigrationSourcePath(searchPaths, dbType) {
104
+ for (const searchPath of searchPaths) {
105
+ const candidatePath = path.join(
106
+ searchPath,
107
+ `prisma-${dbType}`,
108
+ 'migrations'
109
+ );
110
+ if (fs.existsSync(candidatePath)) {
111
+ return candidatePath;
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+
117
+ function getMigrationDestinationPath(layerNodeModules, clientPackage) {
118
+ return path.join(layerNodeModules, clientPackage, 'migrations');
119
+ }
120
+
121
+ /**
122
+ * Build list of required file paths for layer verification
123
+ * Different databases have different deployment patterns:
124
+ * - PostgreSQL: Uses migrations (prisma migrate) - requires migration_lock.toml
125
+ * - MongoDB: Uses schema push (prisma db push) - NO migrations directory
126
+ *
127
+ * @param {Array} clientPackages - Generated client packages to include (e.g., ['generated/prisma-postgresql'])
128
+ * @returns {Array} List of required file paths that must exist in the layer
129
+ */
130
+ function getRequiredLayerPaths(clientPackages) {
131
+ const requiredPaths = [
132
+ // Base Prisma client runtime files (always required)
133
+ '@prisma/client/runtime',
134
+ '@prisma/client/index.d.ts',
135
+ ];
136
+
137
+ // Add schema.prisma for each database client
138
+ for (const pkg of clientPackages) {
139
+ requiredPaths.push(`${pkg}/schema.prisma`);
140
+ }
141
+
142
+ // Add migrations ONLY for PostgreSQL (MongoDB uses schema push, no migrations)
143
+ for (const pkg of clientPackages) {
144
+ const dbType = pkg.replace('generated/prisma-', '');
145
+ if (dbType === 'postgresql') {
146
+ requiredPaths.push(`${pkg}/migrations/migration_lock.toml`);
147
+ }
148
+ }
149
+
150
+ return requiredPaths;
151
+ }
152
+
153
+ // Configuration
154
+ // Script runs from integration project root (e.g., backend/)
155
+ // and reads Prisma packages from @friggframework/core
156
+ const PROJECT_ROOT = process.cwd();
157
+ const CORE_PACKAGE_PATH = findCorePackage(PROJECT_ROOT);
158
+ const LAYER_OUTPUT_PATH = path.join(PROJECT_ROOT, 'layers/prisma');
159
+ const LAYER_NODE_MODULES = path.join(LAYER_OUTPUT_PATH, 'nodejs/node_modules');
160
+
161
+ // Binary patterns to remove (non-rhel)
162
+ const BINARY_PATTERNS_TO_REMOVE = [
163
+ '*darwin*',
164
+ '*debian*',
165
+ '*linux-arm*',
166
+ '*linux-musl*',
167
+ '*windows*',
168
+ ];
169
+
170
+ // Files to remove for size optimization
171
+ const FILES_TO_REMOVE = [
172
+ '*.map', // Source maps (37MB savings)
173
+ '*.md', // Markdown files
174
+ 'LICENSE*', // License files
175
+ 'CHANGELOG*', // Changelog files
176
+ '*.test.js', // Test files
177
+ '*.spec.js', // Spec files
178
+ '*mysql.wasm*', // MySQL WASM files (not needed for PostgreSQL)
179
+ '*cockroachdb.wasm*', // CockroachDB WASM files
180
+ '*sqlite.wasm*', // SQLite WASM files
181
+ '*sqlserver.wasm*', // SQL Server WASM files
182
+ ];
183
+
184
+ // ANSI color codes for output
185
+ const colors = {
186
+ reset: '\x1b[0m',
187
+ bright: '\x1b[1m',
188
+ green: '\x1b[32m',
189
+ yellow: '\x1b[33m',
190
+ blue: '\x1b[34m',
191
+ red: '\x1b[31m',
192
+ };
193
+
194
+ function log(message, color = 'reset') {
195
+ console.log(`${colors[color]}${message}${colors.reset}`);
196
+ }
197
+
198
+ function logStep(step, message) {
199
+ log(`\n[${step}] ${message}`, 'blue');
200
+ }
201
+
202
+ function logSuccess(message) {
203
+ log(`✓ ${message}`, 'green');
204
+ }
205
+
206
+ function logWarning(message) {
207
+ log(`⚠ ${message}`, 'yellow');
208
+ }
209
+
210
+ function logError(message) {
211
+ log(`✗ ${message}`, 'red');
212
+ }
213
+
214
+ /**
215
+ * Get directory size in MB
216
+ */
217
+ function getDirectorySize(dirPath) {
218
+ try {
219
+ const output = execSync(`du -sm "${dirPath}"`, { encoding: 'utf8' });
220
+ const size = parseInt(output.split('\t')[0], 10);
221
+ return size;
222
+ } catch (error) {
223
+ logWarning(`Could not calculate directory size: ${error.message}`);
224
+ return 0;
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Clean existing layer directory
230
+ */
231
+ async function cleanLayerDirectory() {
232
+ logStep(1, 'Cleaning existing layer directory');
233
+
234
+ if (await fs.pathExists(LAYER_OUTPUT_PATH)) {
235
+ await fs.remove(LAYER_OUTPUT_PATH);
236
+ logSuccess(`Removed existing layer at ${LAYER_OUTPUT_PATH}`);
237
+ } else {
238
+ log('No existing layer to clean');
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Create layer directory structure
244
+ */
245
+ async function createLayerStructure() {
246
+ logStep(2, 'Creating layer directory structure');
247
+
248
+ await fs.ensureDir(LAYER_NODE_MODULES);
249
+ logSuccess(`Created ${LAYER_NODE_MODULES}`);
250
+ }
251
+
252
+ /**
253
+ * Install Prisma client directly into layer (RUNTIME ONLY - NO CLI)
254
+ *
255
+ * The Prisma CLI is NOT included in this layer to keep it small.
256
+ * For migrations, the dbMigrate function has its own separate packaging with CLI.
257
+ */
258
+ async function installPrismaPackages() {
259
+ logStep(3, 'Installing Prisma runtime client (CLI excluded)');
260
+
261
+ // Create a minimal package.json with ONLY the runtime client
262
+ const dependencies = {
263
+ '@prisma/client': '^6.16.3',
264
+ };
265
+
266
+ log(' Runtime client only - CLI excluded (saves ~82MB)', 'green');
267
+
268
+ const layerPackageJson = {
269
+ name: 'prisma-lambda-layer',
270
+ version: '1.0.0',
271
+ private: true,
272
+ dependencies,
273
+ };
274
+
275
+ const packageJsonPath = path.join(LAYER_OUTPUT_PATH, 'nodejs/package.json');
276
+ await fs.writeJson(packageJsonPath, layerPackageJson, { spaces: 2 });
277
+ logSuccess('Created layer package.json');
278
+
279
+ // Install Prisma packages with Lambda binary target
280
+ // Setting PRISMA_CLI_BINARY_TARGETS ensures only rhel-openssl-3.0.x binary is downloaded
281
+ log('Installing @prisma/client for AWS Lambda (rhel-openssl-3.0.x)...');
282
+ try {
283
+ const env = {
284
+ ...process.env,
285
+ PRISMA_CLI_BINARY_TARGETS: 'rhel-openssl-3.0.x',
286
+ };
287
+
288
+ execSync('npm install --omit=dev --no-package-lock', {
289
+ cwd: path.join(LAYER_OUTPUT_PATH, 'nodejs'),
290
+ stdio: 'inherit',
291
+ env,
292
+ });
293
+ logSuccess('Prisma packages installed with Lambda binary target');
294
+ } catch (error) {
295
+ throw new Error(`Failed to install Prisma packages: ${error.message}`);
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Copy generated Prisma clients from @friggframework/core to layer
301
+ * @param {Array} clientPackages - List of generated client packages to copy
302
+ */
303
+ async function copyPrismaPackages(clientPackages) {
304
+ logStep(4, 'Copying generated Prisma clients from @friggframework/core');
305
+
306
+ // Copy the generated clients from core based on database config
307
+ // Packages can be in:
308
+ // 1. Core's own node_modules (if not hoisted)
309
+ // 2. Project root node_modules (if hoisted from project)
310
+ // 3. Workspace root node_modules (where core is located - handles hoisting)
311
+ // 4. Core package itself (for generated/ directories)
312
+ const workspaceNodeModules = path.join(
313
+ path.dirname(CORE_PACKAGE_PATH),
314
+ '..'
315
+ );
316
+ const searchPaths = [
317
+ path.join(CORE_PACKAGE_PATH, 'node_modules'), // Core's own node_modules
318
+ path.join(PROJECT_ROOT, 'node_modules'), // Project node_modules
319
+ workspaceNodeModules, // Workspace root node_modules
320
+ CORE_PACKAGE_PATH, // Core package itself (for generated/)
321
+ ];
322
+
323
+ let copiedCount = 0;
324
+ let missingPackages = [];
325
+
326
+ for (const pkg of clientPackages) {
327
+ let sourcePath = null;
328
+
329
+ // Try to find package in search paths
330
+ for (const searchPath of searchPaths) {
331
+ const candidatePath = path.join(searchPath, pkg);
332
+ if (await fs.pathExists(candidatePath)) {
333
+ sourcePath = candidatePath;
334
+ break;
335
+ }
336
+ }
337
+
338
+ if (sourcePath) {
339
+ const destPath = path.join(LAYER_NODE_MODULES, pkg);
340
+ await fs.copy(sourcePath, destPath, {
341
+ dereference: true, // Follow symlinks
342
+ filter: (src) => {
343
+ // Skip node_modules within Prisma packages
344
+ return !src.includes('/node_modules/node_modules/');
345
+ },
346
+ });
347
+ const fromLocation = sourcePath.includes(
348
+ '@friggframework/core/generated'
349
+ )
350
+ ? 'core package (generated)'
351
+ : sourcePath.includes('@friggframework/core/node_modules')
352
+ ? 'core node_modules'
353
+ : 'workspace';
354
+ logSuccess(`Copied ${pkg} (from ${fromLocation})`);
355
+ copiedCount++;
356
+ } else {
357
+ missingPackages.push(pkg);
358
+ logWarning(`Package not found: ${pkg}`);
359
+ }
360
+ }
361
+
362
+ if (missingPackages.length > 0) {
363
+ throw new Error(
364
+ `Missing generated Prisma clients: ${missingPackages.join(
365
+ ', '
366
+ )}.\n` +
367
+ 'Ensure @friggframework/core has generated Prisma clients (run "npm run prisma:generate" in core package).'
368
+ );
369
+ }
370
+
371
+ logSuccess(
372
+ `Copied ${copiedCount} generated client packages from @friggframework/core`
373
+ );
374
+ }
375
+
376
+ async function copyMigrations(clientPackages) {
377
+ logStep(5, 'Copying migrations from @friggframework/core');
378
+
379
+ const workspaceNodeModules = path.join(
380
+ path.dirname(CORE_PACKAGE_PATH),
381
+ '..'
382
+ );
383
+ const searchPaths = [
384
+ path.join(CORE_PACKAGE_PATH, 'node_modules'),
385
+ path.join(PROJECT_ROOT, 'node_modules'),
386
+ workspaceNodeModules,
387
+ CORE_PACKAGE_PATH,
388
+ ];
389
+
390
+ const migrations = getMigrationsPackages(clientPackages);
391
+ let copiedCount = 0;
392
+
393
+ for (const { dbType, clientPackage } of migrations) {
394
+ const sourcePath = getMigrationSourcePath(searchPaths, dbType);
395
+
396
+ if (sourcePath) {
397
+ const destPath = getMigrationDestinationPath(
398
+ LAYER_NODE_MODULES,
399
+ clientPackage
400
+ );
401
+ await fs.copy(sourcePath, destPath, { dereference: true });
402
+
403
+ const fromLocation = sourcePath.includes(
404
+ '@friggframework/core/prisma'
405
+ )
406
+ ? 'core package'
407
+ : 'workspace';
408
+ logSuccess(
409
+ `Copied migrations for ${dbType} (from ${fromLocation})`
410
+ );
411
+ copiedCount++;
412
+ } else {
413
+ logWarning(
414
+ `Migrations not found for ${dbType} - this may cause migration failures`
415
+ );
416
+ }
417
+ }
418
+
419
+ if (copiedCount > 0) {
420
+ logSuccess(
421
+ `Copied migrations for ${copiedCount} database ${
422
+ copiedCount === 1 ? 'type' : 'types'
423
+ }`
424
+ );
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Remove unnecessary files to reduce layer size
430
+ */
431
+ async function removeUnnecessaryFiles() {
432
+ logStep(6, 'Removing unnecessary files (source maps, docs, tests)');
433
+
434
+ let removedCount = 0;
435
+ let totalSize = 0;
436
+
437
+ for (const pattern of FILES_TO_REMOVE) {
438
+ try {
439
+ // Find files matching the pattern
440
+ const findCmd = `find "${LAYER_NODE_MODULES}" -name "${pattern}" -type f 2>/dev/null || true`;
441
+ const files = execSync(findCmd, { encoding: 'utf8' })
442
+ .split('\n')
443
+ .filter((f) => f.trim());
444
+
445
+ for (const file of files) {
446
+ if (await fs.pathExists(file)) {
447
+ const stats = await fs.stat(file);
448
+ totalSize += stats.size;
449
+ await fs.remove(file);
450
+ removedCount++;
451
+ }
452
+ }
453
+ } catch (error) {
454
+ logWarning(`Error removing ${pattern}: ${error.message}`);
455
+ }
456
+ }
457
+
458
+ if (removedCount > 0) {
459
+ const sizeMB = (totalSize / (1024 * 1024)).toFixed(2);
460
+ logSuccess(
461
+ `Removed ${removedCount} unnecessary files (saved ${sizeMB} MB)`
462
+ );
463
+ } else {
464
+ log('No unnecessary files found to remove');
465
+ }
466
+ }
467
+
468
+ /**
469
+ * Remove non-rhel engine binaries to reduce layer size
470
+ */
471
+ async function removeNonRhelBinaries() {
472
+ logStep(7, 'Removing non-rhel engine binaries');
473
+
474
+ let removedCount = 0;
475
+ let totalSize = 0;
476
+
477
+ for (const pattern of BINARY_PATTERNS_TO_REMOVE) {
478
+ try {
479
+ // Find files matching the pattern
480
+ const findCmd = `find "${LAYER_NODE_MODULES}" -name "${pattern}" 2>/dev/null || true`;
481
+ const files = execSync(findCmd, { encoding: 'utf8' })
482
+ .split('\n')
483
+ .filter((f) => f.trim());
484
+
485
+ for (const file of files) {
486
+ if (await fs.pathExists(file)) {
487
+ const stats = await fs.stat(file);
488
+ totalSize += stats.size;
489
+ await fs.remove(file);
490
+ removedCount++;
491
+ }
492
+ }
493
+ } catch (error) {
494
+ logWarning(`Error removing ${pattern}: ${error.message}`);
495
+ }
496
+ }
497
+
498
+ if (removedCount > 0) {
499
+ const sizeMB = (totalSize / (1024 * 1024)).toFixed(2);
500
+ logSuccess(
501
+ `Removed ${removedCount} non-rhel binaries (saved ${sizeMB} MB)`
502
+ );
503
+ } else {
504
+ log('No non-rhel binaries found to remove');
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Verify rhel binaries are present
510
+ * @param {Array} expectedClients - List of client packages that should have binaries
511
+ */
512
+ async function verifyRhelBinaries(expectedClients) {
513
+ logStep(8, 'Verifying rhel-openssl-3.0.x binaries are present');
514
+
515
+ try {
516
+ const findCmd = `find "${LAYER_NODE_MODULES}" -name "*rhel-openssl-3.0.x*" 2>/dev/null || true`;
517
+ const rhelFiles = execSync(findCmd, { encoding: 'utf8' })
518
+ .split('\n')
519
+ .filter((f) => f.trim());
520
+
521
+ if (rhelFiles.length === 0) {
522
+ throw new Error(
523
+ 'No rhel-openssl-3.0.x binaries found!\n' +
524
+ 'Check that Prisma schemas have binaryTargets = ["native", "rhel-openssl-3.0.x"]'
525
+ );
526
+ }
527
+
528
+ const expectedCount = expectedClients.length;
529
+ logSuccess(
530
+ `Found ${rhelFiles.length} rhel-openssl-3.0.x ${
531
+ rhelFiles.length === 1 ? 'binary' : 'binaries'
532
+ } (expected ${expectedCount})`
533
+ );
534
+
535
+ // Show the binaries found
536
+ rhelFiles.forEach((file) => {
537
+ const relativePath = path.relative(LAYER_NODE_MODULES, file);
538
+ log(` - ${relativePath}`, 'reset');
539
+ });
540
+ } catch (error) {
541
+ throw new Error(`Binary verification failed: ${error.message}`);
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Verify required files exist
547
+ * Runtime layer should NOT have CLI files
548
+ * @param {Array} clientPackages - Generated client packages that were included
549
+ */
550
+ async function verifyLayerStructure(clientPackages) {
551
+ logStep(9, 'Verifying layer structure (runtime only)');
552
+
553
+ // Get required paths based on database types
554
+ const requiredPaths = getRequiredLayerPaths(clientPackages);
555
+
556
+ // Verify CLI is NOT present (keeps layer small)
557
+ const forbiddenPaths = ['prisma/build', '.bin/prisma'];
558
+
559
+ let allPresent = true;
560
+
561
+ for (const requiredPath of requiredPaths) {
562
+ const fullPath = path.join(LAYER_NODE_MODULES, requiredPath);
563
+ if (await fs.pathExists(fullPath)) {
564
+ log(` ✓ ${requiredPath}`, 'green');
565
+ } else {
566
+ log(` ✗ ${requiredPath} (missing)`, 'red');
567
+ allPresent = false;
568
+ }
569
+ }
570
+
571
+ if (!allPresent) {
572
+ throw new Error(
573
+ 'Layer structure verification failed - missing required files'
574
+ );
575
+ }
576
+
577
+ logSuccess('All required runtime files present');
578
+
579
+ // Verify CLI is NOT present
580
+ for (const forbiddenPath of forbiddenPaths) {
581
+ const fullPath = path.join(LAYER_NODE_MODULES, forbiddenPath);
582
+ if (await fs.pathExists(fullPath)) {
583
+ logWarning(
584
+ ` ⚠ ${forbiddenPath} found (should be excluded for minimal layer)`
585
+ );
586
+ }
587
+ }
588
+ }
589
+
590
+ /**
591
+ * Calculate and display final layer size
592
+ */
593
+ async function displayLayerSummary() {
594
+ logStep(10, 'Layer build summary');
595
+
596
+ const layerSizeMB = getDirectorySize(LAYER_OUTPUT_PATH);
597
+
598
+ log('\n' + '='.repeat(60), 'bright');
599
+ log(' Prisma Lambda Layer Built Successfully!', 'bright');
600
+ log('='.repeat(60), 'bright');
601
+
602
+ log(`\nLayer location: ${LAYER_OUTPUT_PATH}`, 'blue');
603
+ log(`Layer size: ~${layerSizeMB} MB`, 'green');
604
+
605
+ log('\nPackages included:', 'bright');
606
+ log(' - @prisma/client (runtime only - ~10-15MB)', 'reset');
607
+ log(' - generated/prisma-postgresql (PostgreSQL client)', 'reset');
608
+ log('\nPackages EXCLUDED for minimal size:', 'bright');
609
+ log(' - prisma CLI (excluded - only in dbMigrate function)', 'yellow');
610
+ log(' - @prisma/engines (minimal - only rhel binary)', 'yellow');
611
+
612
+ log('\nNext steps:', 'bright');
613
+ log(
614
+ ' 1. Verify layer structure: ls -lah layers/prisma/nodejs/node_modules/',
615
+ 'reset'
616
+ );
617
+ log(' 2. Deploy to AWS: frigg deploy --stage dev', 'reset');
618
+ log(
619
+ ' 3. Check function sizes in Lambda console (should be ~45-55MB)',
620
+ 'reset'
621
+ );
622
+
623
+ log('\nSee LAMBDA-LAYER-PRISMA.md for complete documentation.', 'yellow');
624
+ log('='.repeat(60) + '\n', 'bright');
625
+ }
626
+
627
+ /**
628
+ * Main build function
629
+ * @param {Object} databaseConfig - Database configuration from AppDefinition.database
630
+ */
631
+ async function buildPrismaLayer(databaseConfig = {}) {
632
+ const startTime = Date.now();
633
+
634
+ log('\n' + '='.repeat(60), 'bright');
635
+ log(' Building Minimal Prisma Lambda Layer (Runtime Only)', 'bright');
636
+ log('='.repeat(60) + '\n', 'bright');
637
+
638
+ // Log paths
639
+ log(`Project root: ${PROJECT_ROOT}`, 'reset');
640
+ log(`Core package: ${CORE_PACKAGE_PATH}`, 'reset');
641
+ log(`Layer output: ${LAYER_OUTPUT_PATH}\n`, 'reset');
642
+
643
+ // Determine which database clients to include
644
+ const clientPackages = getGeneratedClientPackages(databaseConfig);
645
+
646
+ try {
647
+ await cleanLayerDirectory();
648
+ await createLayerStructure();
649
+ await installPrismaPackages(); // Install runtime client only (NO CLI)
650
+ await copyPrismaPackages(clientPackages); // Copy generated clients from core
651
+ await copyMigrations(clientPackages); // Copy migrations from core
652
+ await removeUnnecessaryFiles(); // Remove source maps, docs, tests (37MB+)
653
+ await removeNonRhelBinaries(); // Remove non-Linux binaries
654
+ await verifyRhelBinaries(clientPackages); // Verify query engines present
655
+ await verifyLayerStructure(clientPackages); // Verify minimal runtime structure
656
+ await displayLayerSummary();
657
+
658
+ const duration = ((Date.now() - startTime) / 1000).toFixed(2);
659
+ log(`Build completed in ${duration}s\n`, 'green');
660
+
661
+ return { success: true, duration };
662
+ } catch (error) {
663
+ logError(`\nBuild failed: ${error.message}`);
664
+
665
+ if (error.stack) {
666
+ log('\nStack trace:', 'red');
667
+ console.error(error.stack);
668
+ }
669
+
670
+ log('\nTroubleshooting:', 'yellow');
671
+ log(
672
+ ' 1. Ensure @friggframework/core has dependencies installed',
673
+ 'reset'
674
+ );
675
+ log(' 2. Run "npm run prisma:generate" in core package', 'reset');
676
+ log(
677
+ ' 3. Check that Prisma schemas have correct binaryTargets',
678
+ 'reset'
679
+ );
680
+ log(' 4. See LAMBDA-LAYER-PRISMA.md for details\n', 'reset');
681
+
682
+ // Throw error instead of exit when used as module
683
+ throw error;
684
+ }
685
+ }
686
+
687
+ // Run the build when executed directly
688
+ if (require.main === module) {
689
+ buildPrismaLayer()
690
+ .then(() => process.exit(0))
691
+ .catch(() => process.exit(1));
692
+ }
693
+
694
+ module.exports = {
695
+ buildPrismaLayer,
696
+ getGeneratedClientPackages,
697
+ getMigrationsPackages,
698
+ getMigrationSourcePath,
699
+ getMigrationDestinationPath,
700
+ getRequiredLayerPaths,
701
+ };