@friggframework/devtools 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.656.6eb85ab.0

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 (102) hide show
  1. package/frigg-cli/README.md +31 -115
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +0 -3
  3. package/frigg-cli/__tests__/unit/commands/deploy.test.js +24 -33
  4. package/frigg-cli/__tests__/unit/commands/doctor.test.js +6 -10
  5. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +0 -18
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +341 -601
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +30 -31
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +2 -6
  9. package/frigg-cli/build-command/index.js +0 -6
  10. package/frigg-cli/deploy-command/index.js +0 -6
  11. package/frigg-cli/generate-command/index.js +0 -1
  12. package/frigg-cli/generate-iam-command.js +0 -1
  13. package/frigg-cli/index.js +5 -22
  14. package/frigg-cli/index.test.js +158 -0
  15. package/frigg-cli/init-command/backend-first-handler.js +551 -395
  16. package/frigg-cli/init-command/index.js +35 -82
  17. package/frigg-cli/install-command/commit-changes.js +8 -40
  18. package/frigg-cli/install-command/environment-variables.js +0 -15
  19. package/frigg-cli/install-command/index.js +21 -96
  20. package/frigg-cli/install-command/install-package.js +4 -77
  21. package/frigg-cli/install-command/integration-file.js +11 -20
  22. package/frigg-cli/install-command/template.js +75 -102
  23. package/frigg-cli/install-command/validate-package.js +4 -36
  24. package/frigg-cli/package.json +1 -1
  25. package/frigg-cli/start-command/index.js +0 -4
  26. package/frigg-cli/start-command/start-command.test.js +0 -3
  27. package/frigg-cli/test/init-command.test.js +2 -9
  28. package/infrastructure/README.md +5 -32
  29. package/infrastructure/__tests__/postgres-config.test.js +836 -245
  30. package/infrastructure/__tests__/scoped-environment.test.js +0 -3
  31. package/infrastructure/__tests__/ssm-preload-node-options.test.js +0 -3
  32. package/infrastructure/__tests__/template-generation.test.js +8 -39
  33. package/infrastructure/create-frigg-infrastructure.js +1 -4
  34. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +98 -80
  35. package/infrastructure/domains/admin-scripts/admin-script-builder.js +2 -8
  36. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +6 -52
  37. package/infrastructure/domains/database/aurora-builder.js +2 -13
  38. package/infrastructure/domains/database/aurora-builder.test.js +0 -22
  39. package/infrastructure/domains/database/migration-builder.js +2 -21
  40. package/infrastructure/domains/database/migration-builder.test.js +6 -61
  41. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +8 -12
  42. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +7 -19
  43. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +8 -12
  44. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +18 -17
  45. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +2 -12
  46. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +1 -8
  47. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +2 -4
  48. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +0 -10
  49. package/infrastructure/domains/integration/integration-builder.js +0 -2
  50. package/infrastructure/domains/integration/integration-builder.test.js +6 -22
  51. package/infrastructure/domains/networking/vpc-builder.js +8 -18
  52. package/infrastructure/domains/networking/vpc-builder.test.js +12 -26
  53. package/infrastructure/domains/security/iam-generator.js +5 -112
  54. package/infrastructure/domains/security/iam-generator.test.js +0 -94
  55. package/infrastructure/domains/shared/cloudformation-discovery.test.js +6 -36
  56. package/infrastructure/domains/shared/environment-builder.js +5 -31
  57. package/infrastructure/domains/shared/environment-builder.test.js +7 -93
  58. package/infrastructure/domains/shared/utilities/base-definition-factory.js +3 -39
  59. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +5 -85
  60. package/infrastructure/domains/shared/utilities/nested-node-modules.js +5 -6
  61. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +26 -20
  62. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +12 -92
  63. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +6 -158
  64. package/infrastructure/infrastructure-composer.js +1 -12
  65. package/infrastructure/infrastructure-composer.test.js +794 -339
  66. package/infrastructure/integration.test.js +381 -0
  67. package/infrastructure/scripts/build-prisma-layer.js +50 -136
  68. package/infrastructure/scripts/build-prisma-layer.test.js +7 -128
  69. package/infrastructure/scripts/build-time-discovery.test.js +3 -18
  70. package/package.json +10 -12
  71. package/frigg-cli/__tests__/unit/commands/init.test.js +0 -688
  72. package/frigg-cli/__tests__/unit/commands/validate-wiring.test.js +0 -92
  73. package/frigg-cli/init-command/deployment-modes.js +0 -7
  74. package/frigg-cli/init-command/safe-path.js +0 -58
  75. package/frigg-cli/init-command/scaffold-dependencies.js +0 -202
  76. package/frigg-cli/install-command/app-definition.js +0 -174
  77. package/frigg-cli/install-command/resolve-module.js +0 -69
  78. package/frigg-cli/templates/backend/README.md +0 -267
  79. package/frigg-cli/templates/backend/env.example +0 -20
  80. package/frigg-cli/templates/backend/gitignore +0 -10
  81. package/frigg-cli/templates/backend/index.js +0 -114
  82. package/frigg-cli/templates/backend/infrastructure.js +0 -20
  83. package/frigg-cli/validate-command/__tests__/init-validation.test.js +0 -63
  84. package/frigg-cli/validate-command/__tests__/integrations-checks.test.js +0 -133
  85. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +0 -443
  86. package/frigg-cli/validate-command/__tests__/validate-command.test.js +0 -262
  87. package/frigg-cli/validate-command/checks/config.js +0 -504
  88. package/frigg-cli/validate-command/checks/integrations.js +0 -274
  89. package/frigg-cli/validate-command/format-report.js +0 -58
  90. package/frigg-cli/validate-command/index.js +0 -107
  91. package/frigg-cli/validate-command/load-app-definition.js +0 -105
  92. package/frigg-cli/validate-command/schema-issues.js +0 -154
  93. package/frigg-cli/validate-command/validate-app-definition.js +0 -60
  94. package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +0 -39
  95. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -284
  96. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +0 -151
  97. package/infrastructure/app-definition-schema-contract.test.js +0 -634
  98. package/infrastructure/create-frigg-infrastructure.test.js +0 -51
  99. package/infrastructure/domains/database/migration-engines.js +0 -93
  100. package/infrastructure/domains/database/migration-engines.test.js +0 -142
  101. package/infrastructure/domains/shared/lambda-architectures.js +0 -113
  102. package/infrastructure/domains/shared/lambda-architectures.test.js +0 -164
@@ -0,0 +1,381 @@
1
+ const fs = require('fs');
2
+ const { composeServerlessDefinition } = require('./serverless-template');
3
+ const { AWSDiscovery } = require('./aws-discovery');
4
+ const { BuildTimeDiscovery } = require('./build-time-discovery');
5
+ const FriggServerlessPlugin = require('../../serverless-plugin/index');
6
+
7
+ // Integration tests for end-to-end AWS discovery and serverless config generation
8
+ describe('VPC/KMS/SSM Integration Tests', () => {
9
+ let mockAWSDiscovery;
10
+ let buildTimeDiscovery;
11
+
12
+ const mockAWSResources = {
13
+ defaultVpcId: 'vpc-12345678',
14
+ defaultSecurityGroupId: 'sg-12345678',
15
+ privateSubnetId1: 'subnet-private-1',
16
+ privateSubnetId2: 'subnet-private-2',
17
+ privateRouteTableId: 'rtb-12345678',
18
+ defaultKmsKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
19
+ };
20
+
21
+ beforeEach(() => {
22
+ // Mock AWSDiscovery to return consistent test data
23
+ mockAWSDiscovery = {
24
+ discoverResources: jest.fn().mockResolvedValue(mockAWSResources),
25
+ findDefaultVpc: jest.fn().mockResolvedValue({ VpcId: mockAWSResources.defaultVpcId }),
26
+ findPrivateSubnets: jest.fn().mockResolvedValue([
27
+ { SubnetId: mockAWSResources.privateSubnetId1 },
28
+ { SubnetId: mockAWSResources.privateSubnetId2 }
29
+ ]),
30
+ findDefaultSecurityGroup: jest.fn().mockResolvedValue({ GroupId: mockAWSResources.defaultSecurityGroupId }),
31
+ findPrivateRouteTable: jest.fn().mockResolvedValue({ RouteTableId: mockAWSResources.privateRouteTableId }),
32
+ findDefaultKmsKey: jest.fn().mockResolvedValue(mockAWSResources.defaultKmsKeyId)
33
+ };
34
+
35
+ jest.doMock('./aws-discovery', () => ({
36
+ AWSDiscovery: jest.fn(() => mockAWSDiscovery)
37
+ }));
38
+
39
+ buildTimeDiscovery = new BuildTimeDiscovery('us-east-1');
40
+ });
41
+
42
+ afterEach(() => {
43
+ jest.clearAllMocks();
44
+ jest.resetModules();
45
+ });
46
+
47
+ describe('End-to-End Serverless Configuration Generation', () => {
48
+ it('should generate complete serverless config with VPC, KMS, and SSM enabled', async () => {
49
+ const appDefinition = {
50
+ name: 'test-frigg-app',
51
+ vpc: { enable: true },
52
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
53
+ ssm: { enable: true },
54
+ integrations: [{
55
+ Definition: {
56
+ name: 'testIntegration'
57
+ }
58
+ }]
59
+ };
60
+
61
+ // Run AWS discovery
62
+ const discoveredResources = await mockAWSDiscovery.discoverResources();
63
+
64
+ // Set environment variables as would happen in build
65
+ process.env.AWS_DISCOVERY_VPC_ID = discoveredResources.defaultVpcId;
66
+ process.env.AWS_DISCOVERY_SECURITY_GROUP_ID = discoveredResources.defaultSecurityGroupId;
67
+ process.env.AWS_DISCOVERY_SUBNET_ID_1 = discoveredResources.privateSubnetId1;
68
+ process.env.AWS_DISCOVERY_SUBNET_ID_2 = discoveredResources.privateSubnetId2;
69
+ process.env.AWS_DISCOVERY_ROUTE_TABLE_ID = discoveredResources.privateRouteTableId;
70
+ process.env.AWS_DISCOVERY_KMS_KEY_ID =discoveredResources.defaultKmsKeyId;
71
+
72
+ // Generate serverless configuration
73
+ const serverlessConfig = composeServerlessDefinition(appDefinition);
74
+
75
+ // Verify VPC configuration
76
+ expect(serverlessConfig.provider.vpc).toBe('${self:custom.vpc.${self:provider.stage}}');
77
+ expect(serverlessConfig.custom.vpc).toEqual({
78
+ '${self:provider.stage}': {
79
+ securityGroupIds: ['${env:AWS_DISCOVERY_SECURITY_GROUP_ID}'],
80
+ subnetIds: [
81
+ '${env:AWS_DISCOVERY_SUBNET_ID_1}',
82
+ '${env:AWS_DISCOVERY_SUBNET_ID_2}'
83
+ ]
84
+ }
85
+ });
86
+
87
+ // Verify VPC Endpoint
88
+ expect(serverlessConfig.resources.Resources.VPCEndpointS3).toEqual({
89
+ Type: 'AWS::EC2::VPCEndpoint',
90
+ Properties: {
91
+ VpcId: '${env:AWS_DISCOVERY_VPC_ID}',
92
+ ServiceName: 'com.amazonaws.${self:provider.region}.s3',
93
+ VpcEndpointType: 'Gateway',
94
+ RouteTableIds: ['${env:AWS_DISCOVERY_ROUTE_TABLE_ID}']
95
+ }
96
+ });
97
+
98
+ // Verify KMS configuration
99
+ expect(serverlessConfig.plugins).toContain('serverless-kms-grants');
100
+ expect(serverlessConfig.provider.environment.KMS_KEY_ARN).toBe('${self:custom.kmsGrants.kmsKeyId}');
101
+ expect(serverlessConfig.custom.kmsGrants).toEqual({
102
+ kmsKeyId: '${env:AWS_DISCOVERY_KMS_KEY_ID}'
103
+ });
104
+
105
+ // Verify KMS IAM permissions
106
+ const kmsPermission = serverlessConfig.provider.iamRoleStatements.find(
107
+ statement => statement.Action.includes('kms:GenerateDataKey')
108
+ );
109
+ expect(kmsPermission).toBeDefined();
110
+
111
+ // Verify SSM configuration (enabled without offload markers -> broad grant only)
112
+ expect(serverlessConfig.provider.layers).toBeUndefined();
113
+ expect(serverlessConfig.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
114
+
115
+ // Verify SSM IAM permissions
116
+ const ssmPermission = serverlessConfig.provider.iamRoleStatements.find(
117
+ statement => statement.Action.includes('ssm:GetParameter')
118
+ );
119
+ expect(ssmPermission).toBeDefined();
120
+
121
+ // Verify integration resources
122
+ expect(serverlessConfig.functions.testIntegration).toBeDefined();
123
+ expect(serverlessConfig.functions.testIntegrationQueueWorker).toBeDefined();
124
+ expect(serverlessConfig.resources.Resources.TestIntegrationQueue).toBeDefined();
125
+
126
+ // Clean up environment
127
+ delete process.env.AWS_DISCOVERY_VPC_ID;
128
+ delete process.env.AWS_DISCOVERY_SECURITY_GROUP_ID;
129
+ delete process.env.AWS_DISCOVERY_SUBNET_ID_1;
130
+ delete process.env.AWS_DISCOVERY_SUBNET_ID_2;
131
+ delete process.env.AWS_DISCOVERY_ROUTE_TABLE_ID;
132
+ delete process.env.AWS_DISCOVERY_KMS_KEY_ID;
133
+ });
134
+
135
+ it('should generate config with only VPC enabled', async () => {
136
+ const appDefinition = {
137
+ name: 'vpc-only-app',
138
+ vpc: { enable: true },
139
+ integrations: []
140
+ };
141
+
142
+ process.env.AWS_DISCOVERY_VPC_ID = mockAWSResources.defaultVpcId;
143
+ process.env.AWS_DISCOVERY_SECURITY_GROUP_ID = mockAWSResources.defaultSecurityGroupId;
144
+ process.env.AWS_DISCOVERY_SUBNET_ID_1 = mockAWSResources.privateSubnetId1;
145
+ process.env.AWS_DISCOVERY_SUBNET_ID_2 = mockAWSResources.privateSubnetId2;
146
+ process.env.AWS_DISCOVERY_ROUTE_TABLE_ID = mockAWSResources.privateRouteTableId;
147
+
148
+ const serverlessConfig = composeServerlessDefinition(appDefinition);
149
+
150
+ // Should have VPC config
151
+ expect(serverlessConfig.provider.vpc).toBeDefined();
152
+ expect(serverlessConfig.custom.vpc).toBeDefined();
153
+ expect(serverlessConfig.resources.Resources.VPCEndpointS3).toBeDefined();
154
+
155
+ // Should not have KMS config
156
+ expect(serverlessConfig.plugins).not.toContain('serverless-kms-grants');
157
+ expect(serverlessConfig.provider.environment.KMS_KEY_ARN).toBeUndefined();
158
+
159
+ // Should not have SSM config
160
+ expect(serverlessConfig.provider.layers).toBeUndefined();
161
+ expect(serverlessConfig.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
162
+
163
+ // Clean up
164
+ delete process.env.AWS_DISCOVERY_VPC_ID;
165
+ delete process.env.AWS_DISCOVERY_SECURITY_GROUP_ID;
166
+ delete process.env.AWS_DISCOVERY_SUBNET_ID_1;
167
+ delete process.env.AWS_DISCOVERY_SUBNET_ID_2;
168
+ delete process.env.AWS_DISCOVERY_ROUTE_TABLE_ID;
169
+ });
170
+
171
+ it('should generate config with only KMS enabled', async () => {
172
+ const appDefinition = {
173
+ name: 'kms-only-app',
174
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
175
+ integrations: []
176
+ };
177
+
178
+ process.env.AWS_DISCOVERY_KMS_KEY_ID =mockAWSResources.defaultKmsKeyId;
179
+
180
+ const serverlessConfig = composeServerlessDefinition(appDefinition);
181
+
182
+ // Should have KMS config
183
+ expect(serverlessConfig.plugins).toContain('serverless-kms-grants');
184
+ expect(serverlessConfig.custom.kmsGrants).toBeDefined();
185
+
186
+ // Should not have VPC config
187
+ expect(serverlessConfig.provider.vpc).toBeUndefined();
188
+
189
+ // Should not have SSM config
190
+ expect(serverlessConfig.provider.layers).toBeUndefined();
191
+
192
+ delete process.env.AWS_DISCOVERY_KMS_KEY_ID;
193
+ });
194
+ });
195
+
196
+ describe('Plugin Integration', () => {
197
+ it('should trigger AWS discovery through serverless plugin', async () => {
198
+ const mockServerless = {
199
+ cli: { log: jest.fn() },
200
+ service: {
201
+ provider: {
202
+ name: 'aws',
203
+ region: 'us-east-1',
204
+ vpc: '${self:custom.vpc.${self:provider.stage}}'
205
+ },
206
+ plugins: ['serverless-kms-grants'],
207
+ custom: {},
208
+ functions: {}
209
+ },
210
+ processedInput: { commands: [] },
211
+ getProvider: jest.fn(() => ({})),
212
+ extendConfiguration: jest.fn()
213
+ };
214
+
215
+ const plugin = new FriggServerlessPlugin(mockServerless, { stage: 'test' });
216
+
217
+ // Mock BuildTimeDiscovery
218
+ const mockBuildTimeDiscovery = {
219
+ preBuildHook: jest.fn().mockResolvedValue(mockAWSResources)
220
+ };
221
+
222
+ jest.doMock('./build-time-discovery', () => ({
223
+ BuildTimeDiscovery: jest.fn(() => mockBuildTimeDiscovery)
224
+ }));
225
+
226
+ // Test the beforePackageInitialize hook
227
+ await plugin.beforePackageInitialize();
228
+
229
+ expect(mockBuildTimeDiscovery.preBuildHook).toHaveBeenCalledWith(
230
+ expect.objectContaining({
231
+ vpc: { enable: true },
232
+ encryption: { fieldLevelEncryptionMethod: 'kms' }
233
+ }),
234
+ 'us-east-1'
235
+ );
236
+
237
+ expect(mockServerless.cli.log).toHaveBeenCalledWith('AWS discovery completed successfully');
238
+ });
239
+
240
+ it('should handle plugin discovery failure gracefully', async () => {
241
+ const mockServerless = {
242
+ cli: { log: jest.fn() },
243
+ service: {
244
+ provider: {
245
+ name: 'aws',
246
+ region: 'us-east-1',
247
+ vpc: '${self:custom.vpc}'
248
+ },
249
+ plugins: [],
250
+ custom: {},
251
+ functions: {}
252
+ },
253
+ processedInput: { commands: [] },
254
+ getProvider: jest.fn(() => ({})),
255
+ extendConfiguration: jest.fn()
256
+ };
257
+
258
+ const plugin = new FriggServerlessPlugin(mockServerless, { stage: 'test' });
259
+
260
+ // Mock BuildTimeDiscovery to fail
261
+ const mockBuildTimeDiscovery = {
262
+ preBuildHook: jest.fn().mockRejectedValue(new Error('AWS API Error'))
263
+ };
264
+
265
+ jest.doMock('./build-time-discovery', () => ({
266
+ BuildTimeDiscovery: jest.fn(() => mockBuildTimeDiscovery)
267
+ }));
268
+
269
+ await plugin.beforePackageInitialize();
270
+
271
+ expect(mockServerless.cli.log).toHaveBeenCalledWith('AWS discovery failed, continuing with deployment...');
272
+ expect(mockServerless.cli.log).toHaveBeenCalledWith('Using fallback values for AWS resources');
273
+
274
+ // Verify fallback values are set
275
+ expect(process.env.AWS_DISCOVERY_VPC_ID).toBe('vpc-fallback');
276
+ expect(process.env.AWS_DISCOVERY_KMS_KEY_ID).toBe('arn:aws:kms:*:*:key/*');
277
+ });
278
+ });
279
+
280
+ describe('Template Variable Replacement', () => {
281
+ it('should replace environment variable placeholders with actual values', () => {
282
+ const template = `
283
+ provider:
284
+ vpc:
285
+ securityGroupIds:
286
+ - \${env:AWS_DISCOVERY_SECURITY_GROUP_ID}
287
+ subnetIds:
288
+ - \${env:AWS_DISCOVERY_SUBNET_ID_1}
289
+ - \${env:AWS_DISCOVERY_SUBNET_ID_2}
290
+ environment:
291
+ KMS_KEY_ARN: \${env:AWS_DISCOVERY_KMS_KEY_ID}
292
+ resources:
293
+ VPCEndpoint:
294
+ Properties:
295
+ VpcId: \${env:AWS_DISCOVERY_VPC_ID}
296
+ `;
297
+
298
+ // Set environment variables
299
+ process.env.AWS_DISCOVERY_VPC_ID = mockAWSResources.defaultVpcId;
300
+ process.env.AWS_DISCOVERY_SECURITY_GROUP_ID = mockAWSResources.defaultSecurityGroupId;
301
+ process.env.AWS_DISCOVERY_SUBNET_ID_1 = mockAWSResources.privateSubnetId1;
302
+ process.env.AWS_DISCOVERY_SUBNET_ID_2 = mockAWSResources.privateSubnetId2;
303
+ process.env.AWS_DISCOVERY_KMS_KEY_ID =mockAWSResources.defaultKmsKeyId;
304
+
305
+ // In a real deployment, serverless framework would resolve these environment variables
306
+ // For testing, we can verify the placeholders are correctly formatted
307
+ expect(template).toContain('${env:AWS_DISCOVERY_VPC_ID}');
308
+ expect(template).toContain('${env:AWS_DISCOVERY_SECURITY_GROUP_ID}');
309
+ expect(template).toContain('${env:AWS_DISCOVERY_SUBNET_ID_1}');
310
+ expect(template).toContain('${env:AWS_DISCOVERY_SUBNET_ID_2}');
311
+ expect(template).toContain('${env:AWS_DISCOVERY_KMS_KEY_ID}');
312
+
313
+ // Clean up
314
+ delete process.env.AWS_DISCOVERY_VPC_ID;
315
+ delete process.env.AWS_DISCOVERY_SECURITY_GROUP_ID;
316
+ delete process.env.AWS_DISCOVERY_SUBNET_ID_1;
317
+ delete process.env.AWS_DISCOVERY_SUBNET_ID_2;
318
+ delete process.env.AWS_DISCOVERY_KMS_KEY_ID;
319
+ });
320
+ });
321
+
322
+ describe('Error Scenarios', () => {
323
+ it('should handle AWS discovery timeout gracefully', async () => {
324
+ const mockFailingDiscovery = {
325
+ discoverResources: jest.fn().mockRejectedValue(new Error('Request timeout'))
326
+ };
327
+
328
+ jest.doMock('./aws-discovery', () => ({
329
+ AWSDiscovery: jest.fn(() => mockFailingDiscovery)
330
+ }));
331
+
332
+ const appDefinition = {
333
+ vpc: { enable: true },
334
+ integrations: []
335
+ };
336
+
337
+ await expect(buildTimeDiscovery.preBuildHook(appDefinition, 'us-east-1')).rejects.toThrow('Request timeout');
338
+ });
339
+
340
+ it('should handle partial AWS resource discovery', async () => {
341
+ const partialResources = {
342
+ defaultVpcId: 'vpc-12345678',
343
+ defaultSecurityGroupId: 'sg-12345678',
344
+ privateSubnetId1: 'subnet-1',
345
+ privateSubnetId2: 'subnet-1', // Same subnet used twice
346
+ privateRouteTableId: 'rtb-12345678',
347
+ defaultKmsKeyId: '*' // Fallback KMS key
348
+ };
349
+
350
+ mockAWSDiscovery.discoverResources.mockResolvedValue(partialResources);
351
+
352
+ const appDefinition = {
353
+ vpc: { enable: true },
354
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
355
+ integrations: []
356
+ };
357
+
358
+ const result = await buildTimeDiscovery.preBuildHook(appDefinition, 'us-east-1');
359
+
360
+ expect(result).toEqual(partialResources);
361
+ expect(result.privateSubnetId2).toBe(result.privateSubnetId1); // Should handle single subnet scenario
362
+ expect(result.defaultKmsKeyId).toBe('*'); // Should handle KMS fallback
363
+ });
364
+ });
365
+
366
+ describe('Multi-Region Support', () => {
367
+ it('should support different AWS regions', async () => {
368
+ const appDefinition = {
369
+ vpc: { enable: true },
370
+ integrations: []
371
+ };
372
+
373
+ const euWestDiscovery = new BuildTimeDiscovery('eu-west-1');
374
+
375
+ await euWestDiscovery.preBuildHook(appDefinition, 'eu-west-1');
376
+
377
+ // Verify that AWSDiscovery was instantiated with correct region
378
+ expect(mockAWSDiscovery.discoverResources).toHaveBeenCalled();
379
+ });
380
+ });
381
+ });
@@ -34,9 +34,6 @@
34
34
  const fs = require('fs-extra');
35
35
  const path = require('path');
36
36
  const { execSync } = require('child_process');
37
- const {
38
- resolveLambdaArchitecture,
39
- } = require('../domains/shared/lambda-architectures');
40
37
 
41
38
  /**
42
39
  * Find @friggframework/core package, handling workspace hoisting
@@ -96,31 +93,6 @@ function getGeneratedClientPackages(databaseConfig = {}) {
96
93
  return packages;
97
94
  }
98
95
 
99
- /**
100
- * Everything the layer contents depend on. The layer manager keys its cache
101
- * on this, so a change in any of them rebuilds the layer.
102
- * @param {Object} options
103
- * @param {Object} options.databaseConfig - Database configuration from AppDefinition.database
104
- * @param {string} options.prismaBinaryTarget - The engine the deployed architecture loads
105
- * @returns {{ prismaBinaryTarget: string, clientPackages: string[], coreVersion: string, prismaClientVersion: string }}
106
- */
107
- function layerBuildInputs({
108
- databaseConfig = {},
109
- prismaBinaryTarget = resolveLambdaArchitecture().prismaBinaryTarget,
110
- } = {}) {
111
- return {
112
- prismaBinaryTarget,
113
- clientPackages: getGeneratedClientPackages(databaseConfig),
114
- coreVersion: fs.readJsonSync(path.join(CORE_PACKAGE_PATH, 'package.json'))
115
- .version,
116
- prismaClientVersion: fs.readJsonSync(
117
- require.resolve('@prisma/client/package.json', {
118
- paths: [CORE_PACKAGE_PATH],
119
- })
120
- ).version,
121
- };
122
- }
123
-
124
96
  function getMigrationsPackages(clientPackages) {
125
97
  return clientPackages.map((pkg) => ({
126
98
  dbType: pkg.replace('generated/prisma-', ''),
@@ -186,34 +158,15 @@ const CORE_PACKAGE_PATH = findCorePackage(PROJECT_ROOT);
186
158
  const LAYER_OUTPUT_PATH = path.join(PROJECT_ROOT, 'layers/prisma');
187
159
  const LAYER_NODE_MODULES = path.join(LAYER_OUTPUT_PATH, 'nodejs/node_modules');
188
160
 
189
- // Binary patterns no Lambda architecture runs
161
+ // Binary patterns to remove (non-rhel)
190
162
  const BINARY_PATTERNS_TO_REMOVE = [
191
163
  '*darwin*',
192
164
  '*debian*',
165
+ '*linux-arm*',
193
166
  '*linux-musl*',
194
167
  '*windows*',
195
168
  ];
196
169
 
197
- const ENGINE_FILE_PREFIXES = [
198
- 'libquery_engine-',
199
- 'query-engine-',
200
- 'schema-engine-',
201
- ];
202
-
203
- /**
204
- * Engine files built for a target other than the one the layer deploys to
205
- * @param {string[]} fileNames - Basenames found in the layer
206
- * @param {string} prismaBinaryTarget - The engine the deployed architecture loads
207
- * @returns {string[]}
208
- */
209
- function engineFilesToRemove(fileNames, prismaBinaryTarget) {
210
- return fileNames.filter(
211
- (name) =>
212
- ENGINE_FILE_PREFIXES.some((prefix) => name.startsWith(prefix)) &&
213
- !name.includes(prismaBinaryTarget)
214
- );
215
- }
216
-
217
170
  // Files to remove for size optimization
218
171
  const FILES_TO_REMOVE = [
219
172
  '*.map', // Source maps (37MB savings)
@@ -323,15 +276,21 @@ async function installPrismaPackages() {
323
276
  await fs.writeJson(packageJsonPath, layerPackageJson, { spaces: 2 });
324
277
  logSuccess('Created layer package.json');
325
278
 
326
- // The runtime client has no engine postinstall; the query engines come
327
- // from the generated clients copied out of @friggframework/core.
328
- log('Installing @prisma/client...');
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)...');
329
282
  try {
283
+ const env = {
284
+ ...process.env,
285
+ PRISMA_CLI_BINARY_TARGETS: 'rhel-openssl-3.0.x',
286
+ };
287
+
330
288
  execSync('npm install --omit=dev --no-package-lock', {
331
289
  cwd: path.join(LAYER_OUTPUT_PATH, 'nodejs'),
332
290
  stdio: 'inherit',
291
+ env,
333
292
  });
334
- logSuccess('Prisma packages installed');
293
+ logSuccess('Prisma packages installed with Lambda binary target');
335
294
  } catch (error) {
336
295
  throw new Error(`Failed to install Prisma packages: ${error.message}`);
337
296
  }
@@ -507,40 +466,23 @@ async function removeUnnecessaryFiles() {
507
466
  }
508
467
 
509
468
  /**
510
- * Remove engine binaries the deployed architecture does not load
511
- * @param {string} prismaBinaryTarget - The engine the deployed architecture loads
469
+ * Remove non-rhel engine binaries to reduce layer size
512
470
  */
513
- async function removeForeignBinaries(prismaBinaryTarget) {
514
- logStep(7, `Removing engine binaries other than ${prismaBinaryTarget}`);
471
+ async function removeNonRhelBinaries() {
472
+ logStep(7, 'Removing non-rhel engine binaries');
515
473
 
516
474
  let removedCount = 0;
517
475
  let totalSize = 0;
518
476
 
519
- const findPatterns = [
520
- ...BINARY_PATTERNS_TO_REMOVE,
521
- ...ENGINE_FILE_PREFIXES.map((prefix) => `${prefix}*`),
522
- ];
523
- for (const pattern of findPatterns) {
477
+ for (const pattern of BINARY_PATTERNS_TO_REMOVE) {
524
478
  try {
525
479
  // Find files matching the pattern
526
480
  const findCmd = `find "${LAYER_NODE_MODULES}" -name "${pattern}" 2>/dev/null || true`;
527
481
  const files = execSync(findCmd, { encoding: 'utf8' })
528
482
  .split('\n')
529
483
  .filter((f) => f.trim());
530
- const foreign = new Set(
531
- engineFilesToRemove(
532
- files.map((f) => path.basename(f)),
533
- prismaBinaryTarget
534
- )
535
- );
536
484
 
537
485
  for (const file of files) {
538
- const isEngine = ENGINE_FILE_PREFIXES.some((prefix) =>
539
- path.basename(file).startsWith(prefix)
540
- );
541
- if (isEngine && !foreign.has(path.basename(file))) {
542
- continue;
543
- }
544
486
  if (await fs.pathExists(file)) {
545
487
  const stats = await fs.stat(file);
546
488
  totalSize += stats.size;
@@ -556,59 +498,48 @@ async function removeForeignBinaries(prismaBinaryTarget) {
556
498
  if (removedCount > 0) {
557
499
  const sizeMB = (totalSize / (1024 * 1024)).toFixed(2);
558
500
  logSuccess(
559
- `Removed ${removedCount} foreign binaries (saved ${sizeMB} MB)`
501
+ `Removed ${removedCount} non-rhel binaries (saved ${sizeMB} MB)`
560
502
  );
561
503
  } else {
562
- log('No foreign binaries found to remove');
504
+ log('No non-rhel binaries found to remove');
563
505
  }
564
506
  }
565
507
 
566
508
  /**
567
- * Verify each generated client holds the target query engine and no other
568
- * Linux engine
569
- * @param {string} layerNodeModules - The layer's nodejs/node_modules
570
- * @param {string} prismaBinaryTarget - The engine the deployed architecture loads
571
- * @param {Array} clientPackages - Generated client packages copied into the layer
572
- * @param {string} coreVersion - The @friggframework/core the clients came from
509
+ * Verify rhel binaries are present
510
+ * @param {Array} expectedClients - List of client packages that should have binaries
573
511
  */
574
- async function verifyTargetBinaries(
575
- layerNodeModules,
576
- prismaBinaryTarget,
577
- clientPackages,
578
- coreVersion
579
- ) {
580
- logStep(8, `Verifying ${prismaBinaryTarget} query engines are present`);
581
-
582
- const expectedEngine = `libquery_engine-${prismaBinaryTarget}.so.node`;
583
- for (const pkg of clientPackages) {
584
- const clientDir = path.join(layerNodeModules, pkg);
585
- const files = (await fs.pathExists(clientDir))
586
- ? await fs.readdir(clientDir)
587
- : [];
512
+ async function verifyRhelBinaries(expectedClients) {
513
+ logStep(8, 'Verifying rhel-openssl-3.0.x binaries are present');
588
514
 
589
- if (!files.includes(expectedEngine)) {
590
- throw new Error(
591
- `Binary verification failed: ${pkg} has no ${expectedEngine}.\n` +
592
- `@friggframework/core ${coreVersion} did not generate the ${prismaBinaryTarget} engine. ` +
593
- `Upgrade to a core release whose Prisma schemas list ${prismaBinaryTarget} in binaryTargets.`
594
- );
595
- }
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());
596
520
 
597
- const otherEngines = engineFilesToRemove(files, prismaBinaryTarget);
598
- if (otherEngines.length > 0) {
521
+ if (rhelFiles.length === 0) {
599
522
  throw new Error(
600
- `Binary verification failed: ${pkg} still holds ${otherEngines.join(
601
- ', '
602
- )} next to ${expectedEngine}.`
523
+ 'No rhel-openssl-3.0.x binaries found!\n' +
524
+ 'Check that Prisma schemas have binaryTargets = ["native", "rhel-openssl-3.0.x"]'
603
525
  );
604
526
  }
605
527
 
606
- log(` - ${pkg}/${expectedEngine}`, 'reset');
607
- }
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
+ );
608
534
 
609
- logSuccess(
610
- `Each of ${clientPackages.length} client(s) holds only ${expectedEngine}`
611
- );
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
+ }
612
543
  }
613
544
 
614
545
  /**
@@ -676,7 +607,7 @@ async function displayLayerSummary() {
676
607
  log(' - generated/prisma-postgresql (PostgreSQL client)', 'reset');
677
608
  log('\nPackages EXCLUDED for minimal size:', 'bright');
678
609
  log(' - prisma CLI (excluded - only in dbMigrate function)', 'yellow');
679
- log(' - @prisma/engines (minimal - only the target engine)', 'yellow');
610
+ log(' - @prisma/engines (minimal - only rhel binary)', 'yellow');
680
611
 
681
612
  log('\nNext steps:', 'bright');
682
613
  log(
@@ -695,14 +626,9 @@ async function displayLayerSummary() {
695
626
 
696
627
  /**
697
628
  * Main build function
698
- * @param {Object} options
699
- * @param {Object} options.databaseConfig - Database configuration from AppDefinition.database
700
- * @param {string} options.prismaBinaryTarget - The engine the deployed architecture loads
629
+ * @param {Object} databaseConfig - Database configuration from AppDefinition.database
701
630
  */
702
- async function buildPrismaLayer({
703
- databaseConfig = {},
704
- prismaBinaryTarget = resolveLambdaArchitecture().prismaBinaryTarget,
705
- } = {}) {
631
+ async function buildPrismaLayer(databaseConfig = {}) {
706
632
  const startTime = Date.now();
707
633
 
708
634
  log('\n' + '='.repeat(60), 'bright');
@@ -712,11 +638,7 @@ async function buildPrismaLayer({
712
638
  // Log paths
713
639
  log(`Project root: ${PROJECT_ROOT}`, 'reset');
714
640
  log(`Core package: ${CORE_PACKAGE_PATH}`, 'reset');
715
- log(`Layer output: ${LAYER_OUTPUT_PATH}`, 'reset');
716
- log(`Prisma binary target: ${prismaBinaryTarget}\n`, 'reset');
717
- const coreVersion = fs.readJsonSync(
718
- path.join(CORE_PACKAGE_PATH, 'package.json')
719
- ).version;
641
+ log(`Layer output: ${LAYER_OUTPUT_PATH}\n`, 'reset');
720
642
 
721
643
  // Determine which database clients to include
722
644
  const clientPackages = getGeneratedClientPackages(databaseConfig);
@@ -728,13 +650,8 @@ async function buildPrismaLayer({
728
650
  await copyPrismaPackages(clientPackages); // Copy generated clients from core
729
651
  await copyMigrations(clientPackages); // Copy migrations from core
730
652
  await removeUnnecessaryFiles(); // Remove source maps, docs, tests (37MB+)
731
- await removeForeignBinaries(prismaBinaryTarget); // Keep only the target's engines
732
- await verifyTargetBinaries(
733
- LAYER_NODE_MODULES,
734
- prismaBinaryTarget,
735
- clientPackages,
736
- coreVersion
737
- );
653
+ await removeNonRhelBinaries(); // Remove non-Linux binaries
654
+ await verifyRhelBinaries(clientPackages); // Verify query engines present
738
655
  await verifyLayerStructure(clientPackages); // Verify minimal runtime structure
739
656
  await displayLayerSummary();
740
657
 
@@ -781,7 +698,4 @@ module.exports = {
781
698
  getMigrationSourcePath,
782
699
  getMigrationDestinationPath,
783
700
  getRequiredLayerPaths,
784
- engineFilesToRemove,
785
- verifyTargetBinaries,
786
- layerBuildInputs,
787
701
  };