@friggframework/devtools 2.0.0-next.121 → 2.0.0-next.123

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 (27) hide show
  1. package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
  2. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  3. package/frigg-cli/__tests__/unit/commands/install.test.js +7 -0
  4. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  5. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  6. package/infrastructure/__tests__/management-api-gateway-routes.test.js +281 -0
  7. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  8. package/infrastructure/__tests__/template-generation.test.js +36 -8
  9. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  10. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  11. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  12. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  13. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  14. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  15. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  16. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  17. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  18. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  19. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  20. package/infrastructure/domains/shared/utilities/base-definition-factory.js +19 -0
  21. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +13 -1
  22. package/infrastructure/infrastructure-composer.test.js +268 -794
  23. package/infrastructure/scripts/build-prisma-layer.test.js +28 -7
  24. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  25. package/package.json +7 -7
  26. package/frigg-cli/index.test.js +0 -158
  27. package/infrastructure/integration.test.js +0 -381
@@ -14,10 +14,18 @@ jest.mock('child_process', () => ({
14
14
  spawn: jest.fn()
15
15
  }));
16
16
 
17
+ // Partial mock: only existsSync is stubbed, the rest of fs stays real (a
18
+ // bare { existsSync } mock breaks any dependency that reads fs.constants).
17
19
  jest.mock('fs', () => ({
20
+ ...jest.requireActual('fs'),
18
21
  existsSync: jest.fn()
19
22
  }));
20
23
 
24
+ // The post-deployment health check calls the doctor command (real AWS).
25
+ jest.mock('../../../doctor-command', () => ({
26
+ doctorCommand: jest.fn().mockResolvedValue(undefined)
27
+ }));
28
+
21
29
  // Require after mocks
22
30
  const { spawn } = require('child_process');
23
31
  const fs = require('fs');
@@ -28,6 +36,8 @@ describe('CLI Command: deploy', () => {
28
36
  let consoleWarnSpy;
29
37
  let consoleErrorSpy;
30
38
  let mockChildProcess;
39
+ let childOutcome;
40
+ let exitSpy;
31
41
 
32
42
  beforeEach(() => {
33
43
  jest.clearAllMocks();
@@ -37,10 +47,18 @@ describe('CLI Command: deploy', () => {
37
47
  consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
38
48
  consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
39
49
 
40
- // Mock child process
50
+ // Mock child process. deployCommand awaits the child's exit, so the mock
51
+ // emits `childOutcome` (default: a clean exit) once its handler is wired.
52
+ childOutcome = { event: 'close', value: 0 };
41
53
  mockChildProcess = {
42
- on: jest.fn()
54
+ on: jest.fn((event, handler) => {
55
+ if (event === childOutcome.event) {
56
+ setImmediate(() => handler(childOutcome.value));
57
+ }
58
+ return mockChildProcess;
59
+ })
43
60
  };
61
+ exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});
44
62
 
45
63
  // Mock successful spawn by default
46
64
  spawn.mockReturnValue(mockChildProcess);
@@ -53,6 +71,7 @@ describe('CLI Command: deploy', () => {
53
71
  consoleLogSpy.mockRestore();
54
72
  consoleWarnSpy.mockRestore();
55
73
  consoleErrorSpy.mockRestore();
74
+ exitSpy.mockRestore();
56
75
  });
57
76
 
58
77
  describe('Success Cases', () => {
@@ -278,43 +297,30 @@ describe('CLI Command: deploy', () => {
278
297
  });
279
298
 
280
299
  describe('Error Handling', () => {
281
- it('should log error when spawn fails', async () => {
282
- const testError = new Error('Spawn failed');
283
-
284
- await deployCommand({ stage: 'dev' });
300
+ it('should log and reject when spawn fails', async () => {
301
+ childOutcome = { event: 'error', value: new Error('Spawn failed') };
285
302
 
286
- // Simulate error event
287
- const errorHandler = mockChildProcess.on.mock.calls.find(
288
- call => call[0] === 'error'
289
- )[1];
290
- errorHandler(testError);
303
+ await expect(deployCommand({ stage: 'dev' })).rejects.toThrow('Spawn failed');
291
304
 
292
305
  expect(consoleErrorSpy).toHaveBeenCalledWith('Error executing command: Spawn failed');
293
306
  });
294
307
 
295
- it('should log when child process exits with non-zero code', async () => {
296
- await deployCommand({ stage: 'dev' });
308
+ it('should log and exit with the code when child process exits non-zero', async () => {
309
+ childOutcome = { event: 'close', value: 1 };
297
310
 
298
- // Simulate close event with error code
299
- const closeHandler = mockChildProcess.on.mock.calls.find(
300
- call => call[0] === 'close'
301
- )[1];
302
- closeHandler(1);
311
+ await deployCommand({ stage: 'dev' });
303
312
 
304
313
  expect(consoleLogSpy).toHaveBeenCalledWith('Child process exited with code 1');
314
+ expect(exitSpy).toHaveBeenCalledWith(1);
305
315
  });
306
316
 
307
317
  it('should NOT log when child process exits with zero code', async () => {
308
318
  await deployCommand({ stage: 'dev' });
309
319
 
310
- // Simulate close event with success code
311
- const closeHandler = mockChildProcess.on.mock.calls.find(
312
- call => call[0] === 'close'
313
- )[1];
314
- closeHandler(0);
315
-
316
320
  // Should not log exit message for success
317
321
  expect(consoleLogSpy).not.toHaveBeenCalledWith('Child process exited with code 0');
322
+ expect(exitSpy).not.toHaveBeenCalled();
323
+ expect(consoleLogSpy).toHaveBeenCalledWith('\n✓ Deployment completed successfully!');
318
324
  });
319
325
  });
320
326
  });
@@ -3,7 +3,9 @@
3
3
  * Tests stack listing, selection, and health check orchestration
4
4
  */
5
5
 
6
- const { describe, test, expect, jest, beforeEach } = require('@jest/globals');
6
+ // `jest` is the injected global: destructuring it from @jest/globals collides
7
+ // with the binding babel-plugin-jest-hoist (Jest 30) injects into the module.
8
+ const { describe, test, expect, beforeEach } = require('@jest/globals');
7
9
 
8
10
  describe('Doctor Command - Stack Listing and Selection', () => {
9
11
  let mockCloudFormationClient;
@@ -138,25 +140,27 @@ describe('Doctor Command - Stack Listing and Selection', () => {
138
140
  {
139
141
  name: 'production-stack',
140
142
  status: 'UPDATE_COMPLETE',
141
- createdTime: new Date('2024-01-15'),
142
- updatedTime: new Date('2024-10-20'),
143
+ // Local-time dates: an ISO date string is UTC midnight,
144
+ // which renders as the previous day west of UTC.
145
+ createdTime: new Date(2024, 0, 15),
146
+ updatedTime: new Date(2024, 9, 20),
143
147
  },
144
148
  {
145
149
  name: 'dev-stack',
146
150
  status: 'CREATE_COMPLETE',
147
- createdTime: new Date('2024-10-01'),
151
+ createdTime: new Date(2024, 9, 1),
148
152
  updatedTime: null,
149
153
  },
150
154
  ];
151
155
 
152
156
  const expectedChoices = [
153
157
  {
154
- name: '✓ production-stack (UPDATE_COMPLETE) - Updated: 10/20/2024',
158
+ name: `✓ production-stack (UPDATE_COMPLETE) - Updated: ${mockStacks[0].updatedTime.toLocaleDateString()}`,
155
159
  value: 'production-stack',
156
160
  description: 'Status: UPDATE_COMPLETE',
157
161
  },
158
162
  {
159
- name: '✓ dev-stack (CREATE_COMPLETE) - Created: 10/1/2024',
163
+ name: `✓ dev-stack (CREATE_COMPLETE) - Created: ${mockStacks[1].createdTime.toLocaleDateString()}`,
160
164
  value: 'dev-stack',
161
165
  description: 'Status: CREATE_COMPLETE',
162
166
  },
@@ -621,6 +621,13 @@ describe('commitChanges', () => {
621
621
  it('commits only the given files and leaves other staged changes alone', () => {
622
622
  const dir = makeTmpDir();
623
623
  git(['init', '-q'], dir);
624
+ // commitChanges spawns git without an explicit env, so it sees the
625
+ // real process environment, not Jest's sandboxed process.env: the
626
+ // GIT_* identity set above never reaches it. Give the repo its own
627
+ // identity so the commit works on CI runners with no git user.
628
+ git(['config', 'user.name', 'Test'], dir);
629
+ git(['config', 'user.email', 'test@example.com'], dir);
630
+ git(['config', 'commit.gpgsign', 'false'], dir);
624
631
  fs.writeFileSync(path.join(dir, 'package.json'), '{}');
625
632
  fs.writeFileSync(path.join(dir, 'unrelated.txt'), 'wip');
626
633
  git(['add', 'unrelated.txt'], dir);
@@ -33,6 +33,17 @@ const {
33
33
  } = require('../../../utils/repo-detection');
34
34
  const { uiCommand } = require('../../../ui-command');
35
35
 
36
+ // uiCommand waits 2 s for the dev servers and opens the browser 1 s later.
37
+ // Drive those timers with fake time instead of sleeping for real (the real
38
+ // waits made this suite take ~40 s and tripped the 5 s default timeout).
39
+ const STARTUP_AND_BROWSER_DELAY_MS = 3100;
40
+
41
+ async function runUi(options) {
42
+ const done = uiCommand(options);
43
+ await jest.advanceTimersByTimeAsync(STARTUP_AND_BROWSER_DELAY_MS);
44
+ return done;
45
+ }
46
+
36
47
  describe('CLI Command: ui', () => {
37
48
  let consoleLogSpy;
38
49
  let consoleErrorSpy;
@@ -43,6 +54,7 @@ describe('CLI Command: ui', () => {
43
54
 
44
55
  beforeEach(() => {
45
56
  jest.clearAllMocks();
57
+ jest.useFakeTimers();
46
58
 
47
59
  // Mock console methods
48
60
  consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
@@ -75,6 +87,7 @@ describe('CLI Command: ui', () => {
75
87
  });
76
88
 
77
89
  afterEach(() => {
90
+ jest.useRealTimers();
78
91
  consoleLogSpy.mockRestore();
79
92
  consoleErrorSpy.mockRestore();
80
93
  processExitSpy.mockRestore();
@@ -84,7 +97,7 @@ describe('CLI Command: ui', () => {
84
97
 
85
98
  describe('Repository Detection', () => {
86
99
  it('should use specified repo path when provided', async () => {
87
- await uiCommand({ repo: '/custom/repo', port: 3001, open: false });
100
+ await runUi({ repo: '/custom/repo', port: 3001, open: false });
88
101
 
89
102
  expect(consoleLogSpy).toHaveBeenCalledWith(
90
103
  expect.stringContaining('Using specified repository')
@@ -92,7 +105,7 @@ describe('CLI Command: ui', () => {
92
105
  });
93
106
 
94
107
  it('should detect current Frigg repository', async () => {
95
- await uiCommand({ port: 3001, open: false });
108
+ await runUi({ port: 3001, open: false });
96
109
 
97
110
  expect(getCurrentRepositoryInfo).toHaveBeenCalled();
98
111
  expect(consoleLogSpy).toHaveBeenCalledWith(
@@ -107,7 +120,7 @@ describe('CLI Command: ui', () => {
107
120
  currentSubPath: 'packages/backend'
108
121
  });
109
122
 
110
- await uiCommand({ port: 3001, open: false });
123
+ await runUi({ port: 3001, open: false });
111
124
 
112
125
  expect(consoleLogSpy).toHaveBeenCalledWith(
113
126
  expect.stringContaining('Currently in subdirectory: packages/backend')
@@ -121,7 +134,7 @@ describe('CLI Command: ui', () => {
121
134
  { path: '/repos/frigg-2', name: 'frigg-2' }
122
135
  ]);
123
136
 
124
- await uiCommand({ port: 3001, open: false });
137
+ await runUi({ port: 3001, open: false });
125
138
 
126
139
  expect(discoverFriggRepositories).toHaveBeenCalled();
127
140
  expect(consoleLogSpy).toHaveBeenCalledWith(
@@ -133,7 +146,7 @@ describe('CLI Command: ui', () => {
133
146
  getCurrentRepositoryInfo.mockResolvedValue(null);
134
147
  discoverFriggRepositories.mockResolvedValue([]);
135
148
 
136
- await uiCommand({ port: 3001, open: false });
149
+ await runUi({ port: 3001, open: false });
137
150
 
138
151
  expect(consoleLogSpy).toHaveBeenCalledWith(
139
152
  expect.stringContaining('No Frigg repositories found')
@@ -144,7 +157,7 @@ describe('CLI Command: ui', () => {
144
157
 
145
158
  describe('Development Mode', () => {
146
159
  it('should spawn backend and frontend in dev mode', async () => {
147
- await uiCommand({ port: 3001, open: false, dev: true });
160
+ await runUi({ port: 3001, open: false, dev: true });
148
161
 
149
162
  expect(mockProcessManager.spawnProcess).toHaveBeenCalledTimes(2);
150
163
  expect(mockProcessManager.spawnProcess).toHaveBeenCalledWith(
@@ -168,7 +181,7 @@ describe('CLI Command: ui', () => {
168
181
  });
169
182
 
170
183
  it('should use default port 3001', async () => {
171
- await uiCommand({ open: false, dev: true });
184
+ await runUi({ open: false, dev: true });
172
185
 
173
186
  expect(mockProcessManager.spawnProcess).toHaveBeenCalledWith(
174
187
  expect.any(String),
@@ -181,7 +194,7 @@ describe('CLI Command: ui', () => {
181
194
  });
182
195
 
183
196
  it('should use custom port when specified', async () => {
184
- await uiCommand({ port: 4000, open: false, dev: true });
197
+ await runUi({ port: 4000, open: false, dev: true });
185
198
 
186
199
  expect(mockProcessManager.spawnProcess).toHaveBeenCalledWith(
187
200
  expect.any(String),
@@ -197,10 +210,7 @@ describe('CLI Command: ui', () => {
197
210
  });
198
211
 
199
212
  it('should print status with correct URLs', async () => {
200
- await uiCommand({ port: 3001, open: false, dev: true });
201
-
202
- // Wait for startup delay (testing async behavior, not mocks)
203
- await new Promise(resolve => setTimeout(resolve, 2100));
213
+ await runUi({ port: 3001, open: false, dev: true });
204
214
 
205
215
  // Verify printStatus called with exact URLs
206
216
  expect(mockProcessManager.printStatus).toHaveBeenCalledWith(
@@ -211,20 +221,14 @@ describe('CLI Command: ui', () => {
211
221
  });
212
222
 
213
223
  it('should open browser when open=true', async () => {
214
- await uiCommand({ port: 3001, open: true, dev: true });
215
-
216
- // Wait for startup + browser delay (testing async behavior, not mocks)
217
- await new Promise(resolve => setTimeout(resolve, 3100));
224
+ await runUi({ port: 3001, open: true, dev: true });
218
225
 
219
226
  // Verify browser opened with correct URL
220
227
  expect(open).toHaveBeenCalledWith('http://localhost:5173');
221
228
  });
222
229
 
223
230
  it('should NOT open browser when open=false', async () => {
224
- await uiCommand({ port: 3001, open: false, dev: true });
225
-
226
- // Wait for startup delay (testing async behavior, not mocks)
227
- await new Promise(resolve => setTimeout(resolve, 3100));
231
+ await runUi({ port: 3001, open: false, dev: true });
228
232
 
229
233
  // Verify browser was not opened
230
234
  expect(open).not.toHaveBeenCalled();
@@ -237,7 +241,7 @@ describe('CLI Command: ui', () => {
237
241
  currentSubPath: null
238
242
  });
239
243
 
240
- await uiCommand({ port: 3001, open: false, dev: true });
244
+ await runUi({ port: 3001, open: false, dev: true });
241
245
 
242
246
  expect(mockProcessManager.spawnProcess).toHaveBeenCalledWith(
243
247
  expect.any(String),
@@ -252,7 +256,7 @@ describe('CLI Command: ui', () => {
252
256
  });
253
257
 
254
258
  it('should set REPOSITORY_INFO as JSON string with correct structure', async () => {
255
- await uiCommand({ port: 3001, open: false, dev: true });
259
+ await runUi({ port: 3001, open: false, dev: true });
256
260
 
257
261
  const call = mockProcessManager.spawnProcess.mock.calls[0];
258
262
  const env = call[3].env;
@@ -275,7 +279,7 @@ describe('CLI Command: ui', () => {
275
279
  { path: '/repos/frigg-1', name: 'frigg-1' }
276
280
  ]);
277
281
 
278
- await uiCommand({ port: 3001, open: false, dev: true });
282
+ await runUi({ port: 3001, open: false, dev: true });
279
283
 
280
284
  const call = mockProcessManager.spawnProcess.mock.calls[0];
281
285
  const env = call[3].env;
@@ -299,7 +303,7 @@ describe('CLI Command: ui', () => {
299
303
  throw error;
300
304
  });
301
305
 
302
- await uiCommand({ port: 3001, open: false, dev: true });
306
+ await runUi({ port: 3001, open: false, dev: true });
303
307
 
304
308
  expect(consoleErrorSpy).toHaveBeenCalledWith(
305
309
  expect.stringContaining('Failed to start Management UI'),
@@ -316,7 +320,7 @@ describe('CLI Command: ui', () => {
316
320
  throw new Error('Generic startup error');
317
321
  });
318
322
 
319
- await uiCommand({ port: 3001, open: false, dev: true });
323
+ await runUi({ port: 3001, open: false, dev: true });
320
324
 
321
325
  expect(consoleErrorSpy).toHaveBeenCalledWith(
322
326
  expect.stringContaining('Failed to start Management UI'),
@@ -328,16 +332,13 @@ describe('CLI Command: ui', () => {
328
332
 
329
333
  describe('Process Management', () => {
330
334
  it('should create ProcessManager instance', async () => {
331
- await uiCommand({ port: 3001, open: false, dev: true });
335
+ await runUi({ port: 3001, open: false, dev: true });
332
336
 
333
337
  expect(ProcessManager).toHaveBeenCalled();
334
338
  });
335
339
 
336
340
  it('should keep process running with stdin.resume', async () => {
337
- await uiCommand({ port: 3001, open: false, dev: true });
338
-
339
- // Wait for startup delay (testing async behavior, not mocks)
340
- await new Promise(resolve => setTimeout(resolve, 2100));
341
+ await runUi({ port: 3001, open: false, dev: true });
341
342
 
342
343
  // Verify stdin.resume called to keep process alive
343
344
  expect(stdinResumeSpy).toHaveBeenCalled();
@@ -51,8 +51,12 @@ describe('frigg-cli dependencies', () => {
51
51
  expect(packageJson.dependencies.commander).toBeDefined();
52
52
  });
53
53
 
54
- it('should have @friggframework/devtools for infrastructure', () => {
55
- expect(packageJson.dependencies['@friggframework/devtools']).toBeDefined();
54
+ // frigg-cli ships inside @friggframework/devtools (14236100), so
55
+ // devtools is a peer, not a runtime dependency — a hard dependency
56
+ // would make the package depend on itself.
57
+ it('should declare @friggframework/devtools as a peer dependency for infrastructure', () => {
58
+ expect(packageJson.peerDependencies['@friggframework/devtools']).toBeDefined();
59
+ expect(packageJson.dependencies['@friggframework/devtools']).toBeUndefined();
56
60
  });
57
61
  });
58
62
 
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Management API ↔ API Gateway route coverage
3
+ *
4
+ * The Management API is an Express app (core's createIntegrationRouter)
5
+ * served by the `auth` Lambda. API Gateway HTTP APIs have no implicit
6
+ * catch-all: a request whose path matches no declared route gets a gateway
7
+ * 404 and never reaches Express. So every route the integration router
8
+ * registers must be covered by an httpApi event on the `auth` function, and
9
+ * no more-specific route on another function may shadow it.
10
+ *
11
+ * The Express routes are read from the live router (not a hard-coded list),
12
+ * so a route added to core later fails this test until the gateway routes
13
+ * are updated alongside it.
14
+ */
15
+
16
+ // Avoid AWS calls: hand the builders a fixed discovery result.
17
+ jest.mock('../domains/shared/resource-discovery', () => {
18
+ const actual = jest.requireActual('../domains/shared/resource-discovery');
19
+ return {
20
+ ...actual,
21
+ gatherDiscoveredResources: jest.fn().mockResolvedValue({
22
+ defaultVpcId: 'vpc-123456',
23
+ vpcCidr: '172.31.0.0/16',
24
+ defaultSecurityGroupId: 'sg-123456',
25
+ privateSubnetId1: 'subnet-123456',
26
+ privateSubnetId2: 'subnet-789012',
27
+ publicSubnetId1: 'subnet-public-1',
28
+ publicSubnetId2: 'subnet-public-2',
29
+ defaultRouteTableId: 'rtb-123456',
30
+ defaultKmsKeyId:
31
+ 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
32
+ existingNatGatewayId: 'nat-default123',
33
+ auroraClusterEndpoint:
34
+ 'test-cluster.cluster-abc123.us-east-1.rds.amazonaws.com',
35
+ auroraPort: 5432,
36
+ auroraEngine: 'aurora-postgresql',
37
+ }),
38
+ };
39
+ });
40
+
41
+ // createIntegrationRouter loads the app definition from the consuming
42
+ // backend; give it an empty one so the router can be built in isolation.
43
+ jest.mock('@friggframework/core/handlers/app-definition-loader', () => ({
44
+ loadAppDefinition: () => ({ integrations: [], userConfig: {} }),
45
+ }));
46
+
47
+ const { composeServerlessDefinition } = require('../infrastructure-composer');
48
+
49
+ // Routes the auth Lambda's handler (core/handlers/routers/auth.js) adds on
50
+ // top of createIntegrationRouter().
51
+ const AUTH_HANDLER_EXTRA_ROUTES = [
52
+ { method: 'GET', path: '/api/integrations/redirect/:appId' },
53
+ ];
54
+
55
+ function getIntegrationRouterRoutes() {
56
+ const { createIntegrationRouter } = require('@friggframework/core');
57
+ // The repository factories pick an adapter from DB_TYPE (or the backend's
58
+ // app definition, which doesn't exist here). Nothing connects.
59
+ const previousDbType = process.env.DB_TYPE;
60
+ process.env.DB_TYPE = 'postgresql';
61
+ let app;
62
+ try {
63
+ app = createIntegrationRouter();
64
+ } finally {
65
+ if (previousDbType === undefined) delete process.env.DB_TYPE;
66
+ else process.env.DB_TYPE = previousDbType;
67
+ }
68
+ const stack = (app._router || app.router).stack;
69
+ const routes = [];
70
+ for (const layer of stack) {
71
+ if (!layer.route) continue;
72
+ for (const method of Object.keys(layer.route.methods)) {
73
+ routes.push({
74
+ method: method === '_all' ? 'ANY' : method.toUpperCase(),
75
+ path: layer.route.path,
76
+ });
77
+ }
78
+ }
79
+ return routes;
80
+ }
81
+
82
+ function getGatewayRoutes(definition) {
83
+ const routes = [];
84
+ for (const [functionName, fn] of Object.entries(definition.functions)) {
85
+ for (const event of fn.events || []) {
86
+ if (!event.httpApi) continue;
87
+ routes.push({
88
+ functionName,
89
+ method: String(event.httpApi.method).toUpperCase(),
90
+ path: event.httpApi.path,
91
+ });
92
+ }
93
+ }
94
+ return routes;
95
+ }
96
+
97
+ const segmentsOf = (p) => p.split('/').filter(Boolean);
98
+
99
+ // Turn an Express path into a concrete request path, e.g.
100
+ // /api/entities/:entityId/options -> /api/entities/sample-entityId/options
101
+ const toConcretePath = (expressPath) =>
102
+ expressPath.replace(/:([A-Za-z0-9_]+)/g, 'sample-$1');
103
+
104
+ /**
105
+ * HTTP API path matching: literal segments match exactly, {param} matches
106
+ * one segment, a trailing {proxy+} greedily matches one or more segments.
107
+ * Returns null on no match, otherwise a specificity descriptor.
108
+ */
109
+ function matchGatewayPath(gatewayPath, requestPath) {
110
+ const g = segmentsOf(gatewayPath);
111
+ const r = segmentsOf(requestPath);
112
+ let literals = 0;
113
+ for (let i = 0; i < g.length; i++) {
114
+ const seg = g[i];
115
+ if (/^\{[^}]+\+\}$/.test(seg)) {
116
+ if (i !== g.length - 1 || r.length <= i) return null;
117
+ return { greedy: true, literals, prefixLength: i };
118
+ }
119
+ if (i >= r.length) return null;
120
+ if (/^\{[^}]+\}$/.test(seg)) continue;
121
+ if (seg !== r[i]) return null;
122
+ literals++;
123
+ }
124
+ if (g.length !== r.length) return null;
125
+ return { greedy: false, literals, prefixLength: g.length };
126
+ }
127
+
128
+ /**
129
+ * Select the route API Gateway would invoke: a non-greedy match beats a
130
+ * greedy one, then more literal segments, then the longer greedy prefix,
131
+ * then an explicit method beats ANY.
132
+ */
133
+ function selectGatewayRoute(gatewayRoutes, method, requestPath) {
134
+ const candidates = gatewayRoutes
135
+ .filter(
136
+ (r) => r.method === 'ANY' || method === 'ANY' || r.method === method
137
+ )
138
+ .map((r) => ({
139
+ route: r,
140
+ match: matchGatewayPath(r.path, requestPath),
141
+ }))
142
+ .filter((c) => c.match);
143
+ candidates.sort(
144
+ (a, b) =>
145
+ Number(a.match.greedy) - Number(b.match.greedy) ||
146
+ b.match.literals - a.match.literals ||
147
+ b.match.prefixLength - a.match.prefixLength ||
148
+ Number(a.route.method === 'ANY') - Number(b.route.method === 'ANY')
149
+ );
150
+ return candidates.length ? candidates[0].route : null;
151
+ }
152
+
153
+ describe('Management API routes are reachable through API Gateway', () => {
154
+ let gatewayRoutes;
155
+ let managementRoutes;
156
+ const originalArgv = process.argv;
157
+
158
+ beforeAll(async () => {
159
+ process.argv = ['node', 'test'];
160
+ process.env.AWS_REGION = 'us-east-1';
161
+ // The builders narrate their progress; keep the test output quiet.
162
+ const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
163
+ const warnSpy = jest
164
+ .spyOn(console, 'warn')
165
+ .mockImplementation(() => {});
166
+ try {
167
+ const definition = await composeServerlessDefinition({
168
+ name: 'route-coverage-app',
169
+ provider: 'aws',
170
+ usePrismaLambdaLayer: false,
171
+ database: { postgres: { enable: true } },
172
+ websockets: { enable: true },
173
+ adminScripts: [
174
+ class ExampleScript {
175
+ static Definition = { name: 'example-script' };
176
+ },
177
+ ],
178
+ admin: { includeBuiltinReports: true },
179
+ integrations: [
180
+ {
181
+ Definition: {
182
+ name: 'acme',
183
+ webhooks: true,
184
+ extensions: {
185
+ inbound: {
186
+ extension: {
187
+ routes: [
188
+ { path: '/events', method: 'POST' },
189
+ ],
190
+ },
191
+ },
192
+ },
193
+ },
194
+ },
195
+ // Integration names share the /api/ namespace with the
196
+ // Management API; make sure they don't shadow it.
197
+ { Definition: { name: 'entities' } },
198
+ ],
199
+ });
200
+ gatewayRoutes = getGatewayRoutes(definition);
201
+ } finally {
202
+ logSpy.mockRestore();
203
+ warnSpy.mockRestore();
204
+ }
205
+ managementRoutes = [
206
+ ...getIntegrationRouterRoutes(),
207
+ ...AUTH_HANDLER_EXTRA_ROUTES,
208
+ ];
209
+ });
210
+
211
+ afterAll(() => {
212
+ process.argv = originalArgv;
213
+ delete process.env.AWS_REGION;
214
+ });
215
+
216
+ it('reads the Management API routes from the core integration router', () => {
217
+ const paths = managementRoutes.map((r) => r.path);
218
+ expect(paths).toEqual(
219
+ expect.arrayContaining([
220
+ '/api/integrations',
221
+ '/api/authorize',
222
+ '/api/entity',
223
+ '/api/entity/options/:credentialId',
224
+ '/api/entities/:entityId',
225
+ ])
226
+ );
227
+ });
228
+
229
+ it('routes every Management API route to the auth function', () => {
230
+ const unreachable = managementRoutes
231
+ .map(({ method, path: expressPath }) => {
232
+ const requestPath = toConcretePath(expressPath);
233
+ const selected = selectGatewayRoute(
234
+ gatewayRoutes,
235
+ method,
236
+ requestPath
237
+ );
238
+ return {
239
+ route: `${method} ${expressPath}`,
240
+ reachedBy: selected
241
+ ? `${selected.method} ${selected.path} -> ${selected.functionName}`
242
+ : 'no API Gateway route',
243
+ ok: selected && selected.functionName === 'auth',
244
+ };
245
+ })
246
+ .filter((r) => !r.ok)
247
+ .map(({ route, reachedBy }) => `${route} (${reachedBy})`);
248
+
249
+ expect(unreachable).toEqual([]);
250
+ });
251
+
252
+ it.each([
253
+ ['GET', '/api/v2/reports', 'reportRouter'],
254
+ ['POST', '/api/v2/reports/daily/run', 'reportRouter'],
255
+ ['GET', '/admin/scripts/example-script', 'adminScriptRouter'],
256
+ ['POST', '/api/acme-integration/webhooks', 'acmeWebhook'],
257
+ ['POST', '/api/acme-integration/inbound/events', 'acme__inbound'],
258
+ ['GET', '/api/acme-integration/custom', 'acme'],
259
+ ['GET', '/api/entities-integration/custom', 'entities'],
260
+ ['POST', '/user/login', 'user'],
261
+ ['GET', '/health/ready', 'health'],
262
+ ])('leaves %s %s on %s', (method, requestPath, functionName) => {
263
+ const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
264
+ expect(selected && selected.functionName).toBe(functionName);
265
+ });
266
+
267
+ it('declares no method + path pair on more than one function', () => {
268
+ const seen = new Map();
269
+ const duplicates = [];
270
+ for (const r of gatewayRoutes) {
271
+ const key = `${r.method} ${r.path}`;
272
+ if (seen.has(key) && seen.get(key) !== r.functionName) {
273
+ duplicates.push(
274
+ `${key}: ${seen.get(key)} and ${r.functionName}`
275
+ );
276
+ }
277
+ seen.set(key, r.functionName);
278
+ }
279
+ expect(duplicates).toEqual([]);
280
+ });
281
+ });