@friggframework/core 2.0.0--canary.461.61382d8.0 → 2.0.0--canary.461.3d6d8ad.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 (120) hide show
  1. package/database/use-cases/check-migration-status-use-case.js +81 -0
  2. package/generated/prisma-mongodb/client.d.ts +1 -0
  3. package/generated/prisma-mongodb/client.js +4 -0
  4. package/generated/prisma-mongodb/default.d.ts +1 -0
  5. package/generated/prisma-mongodb/default.js +4 -0
  6. package/generated/prisma-mongodb/edge.d.ts +1 -0
  7. package/generated/prisma-mongodb/edge.js +336 -0
  8. package/generated/prisma-mongodb/index-browser.js +318 -0
  9. package/generated/prisma-mongodb/index.d.ts +22993 -0
  10. package/generated/prisma-mongodb/index.js +361 -0
  11. package/generated/prisma-mongodb/package.json +183 -0
  12. package/generated/prisma-mongodb/query-engine-debian-openssl-3.0.x +0 -0
  13. package/generated/prisma-mongodb/query-engine-rhel-openssl-3.0.x +0 -0
  14. package/generated/prisma-mongodb/runtime/binary.d.ts +1 -0
  15. package/generated/prisma-mongodb/runtime/binary.js +289 -0
  16. package/generated/prisma-mongodb/runtime/edge-esm.js +34 -0
  17. package/generated/prisma-mongodb/runtime/edge.js +34 -0
  18. package/generated/prisma-mongodb/runtime/index-browser.d.ts +370 -0
  19. package/generated/prisma-mongodb/runtime/index-browser.js +16 -0
  20. package/generated/prisma-mongodb/runtime/library.d.ts +3977 -0
  21. package/generated/prisma-mongodb/runtime/react-native.js +83 -0
  22. package/generated/prisma-mongodb/runtime/wasm-compiler-edge.js +84 -0
  23. package/generated/prisma-mongodb/runtime/wasm-engine-edge.js +36 -0
  24. package/generated/prisma-mongodb/schema.prisma +364 -0
  25. package/generated/prisma-mongodb/wasm-edge-light-loader.mjs +4 -0
  26. package/generated/prisma-mongodb/wasm-worker-loader.mjs +4 -0
  27. package/generated/prisma-mongodb/wasm.d.ts +1 -0
  28. package/generated/prisma-mongodb/wasm.js +343 -0
  29. package/generated/prisma-postgresql/client.d.ts +1 -0
  30. package/generated/prisma-postgresql/client.js +4 -0
  31. package/generated/prisma-postgresql/default.d.ts +1 -0
  32. package/generated/prisma-postgresql/default.js +4 -0
  33. package/generated/prisma-postgresql/edge.d.ts +1 -0
  34. package/generated/prisma-postgresql/edge.js +358 -0
  35. package/generated/prisma-postgresql/index-browser.js +340 -0
  36. package/generated/prisma-postgresql/index.d.ts +25171 -0
  37. package/generated/prisma-postgresql/index.js +383 -0
  38. package/generated/prisma-postgresql/package.json +183 -0
  39. package/generated/prisma-postgresql/query-engine-debian-openssl-3.0.x +0 -0
  40. package/generated/prisma-postgresql/query-engine-rhel-openssl-3.0.x +0 -0
  41. package/generated/prisma-postgresql/query_engine_bg.js +2 -0
  42. package/generated/prisma-postgresql/query_engine_bg.wasm +0 -0
  43. package/generated/prisma-postgresql/runtime/binary.d.ts +1 -0
  44. package/generated/prisma-postgresql/runtime/binary.js +289 -0
  45. package/generated/prisma-postgresql/runtime/edge-esm.js +34 -0
  46. package/generated/prisma-postgresql/runtime/edge.js +34 -0
  47. package/generated/prisma-postgresql/runtime/index-browser.d.ts +370 -0
  48. package/generated/prisma-postgresql/runtime/index-browser.js +16 -0
  49. package/generated/prisma-postgresql/runtime/library.d.ts +3977 -0
  50. package/generated/prisma-postgresql/runtime/react-native.js +83 -0
  51. package/generated/prisma-postgresql/runtime/wasm-compiler-edge.js +84 -0
  52. package/generated/prisma-postgresql/runtime/wasm-engine-edge.js +36 -0
  53. package/generated/prisma-postgresql/schema.prisma +347 -0
  54. package/generated/prisma-postgresql/wasm-edge-light-loader.mjs +4 -0
  55. package/generated/prisma-postgresql/wasm-worker-loader.mjs +4 -0
  56. package/generated/prisma-postgresql/wasm.d.ts +1 -0
  57. package/generated/prisma-postgresql/wasm.js +365 -0
  58. package/handlers/routers/db-migration.js +52 -0
  59. package/package.json +5 -5
  60. package/application/commands/integration-commands.test.js +0 -123
  61. package/core/Worker.test.js +0 -159
  62. package/database/encryption/encryption-integration.test.js +0 -553
  63. package/database/encryption/encryption-schema-registry.test.js +0 -392
  64. package/database/encryption/field-encryption-service.test.js +0 -525
  65. package/database/encryption/mongo-decryption-fix-verification.test.js +0 -348
  66. package/database/encryption/postgres-decryption-fix-verification.test.js +0 -371
  67. package/database/encryption/postgres-relation-decryption.test.js +0 -245
  68. package/database/encryption/prisma-encryption-extension.test.js +0 -439
  69. package/database/repositories/migration-status-repository-s3.test.js +0 -158
  70. package/database/use-cases/check-encryption-health-use-case.test.js +0 -192
  71. package/database/use-cases/get-migration-status-use-case.test.js +0 -171
  72. package/database/use-cases/run-database-migration-use-case.test.js +0 -310
  73. package/database/use-cases/trigger-database-migration-use-case.test.js +0 -250
  74. package/database/utils/prisma-runner.test.js +0 -486
  75. package/encrypt/Cryptor.test.js +0 -144
  76. package/errors/base-error.test.js +0 -32
  77. package/errors/fetch-error.test.js +0 -79
  78. package/errors/halt-error.test.js +0 -11
  79. package/errors/validation-errors.test.js +0 -120
  80. package/handlers/auth-flow.integration.test.js +0 -147
  81. package/handlers/integration-event-dispatcher.test.js +0 -209
  82. package/handlers/routers/db-migration.test.js +0 -51
  83. package/handlers/routers/health.test.js +0 -210
  84. package/handlers/routers/integration-webhook-routers.test.js +0 -126
  85. package/handlers/use-cases/check-integrations-health-use-case.test.js +0 -125
  86. package/handlers/webhook-flow.integration.test.js +0 -356
  87. package/handlers/workers/db-migration.test.js +0 -50
  88. package/handlers/workers/integration-defined-workers.test.js +0 -184
  89. package/integrations/tests/integration-router-multi-auth.test.js +0 -369
  90. package/integrations/tests/use-cases/create-integration.test.js +0 -131
  91. package/integrations/tests/use-cases/delete-integration-for-user.test.js +0 -150
  92. package/integrations/tests/use-cases/find-integration-context-by-external-entity-id.test.js +0 -92
  93. package/integrations/tests/use-cases/get-integration-for-user.test.js +0 -150
  94. package/integrations/tests/use-cases/get-integration-instance.test.js +0 -176
  95. package/integrations/tests/use-cases/get-integrations-for-user.test.js +0 -176
  96. package/integrations/tests/use-cases/get-possible-integrations.test.js +0 -188
  97. package/integrations/tests/use-cases/update-integration-messages.test.js +0 -142
  98. package/integrations/tests/use-cases/update-integration-status.test.js +0 -103
  99. package/integrations/tests/use-cases/update-integration.test.js +0 -141
  100. package/integrations/use-cases/create-process.test.js +0 -178
  101. package/integrations/use-cases/get-process.test.js +0 -190
  102. package/integrations/use-cases/load-integration-context-full.test.js +0 -329
  103. package/integrations/use-cases/load-integration-context.test.js +0 -114
  104. package/integrations/use-cases/update-process-metrics.test.js +0 -308
  105. package/integrations/use-cases/update-process-state.test.js +0 -256
  106. package/lambda/TimeoutCatcher.test.js +0 -68
  107. package/logs/logger.test.js +0 -76
  108. package/modules/module-hydration.test.js +0 -205
  109. package/modules/requester/requester.test.js +0 -28
  110. package/queues/queuer-util.test.js +0 -132
  111. package/user/tests/use-cases/create-individual-user.test.js +0 -24
  112. package/user/tests/use-cases/create-organization-user.test.js +0 -28
  113. package/user/tests/use-cases/create-token-for-user-id.test.js +0 -19
  114. package/user/tests/use-cases/get-user-from-adopter-jwt.test.js +0 -113
  115. package/user/tests/use-cases/get-user-from-bearer-token.test.js +0 -64
  116. package/user/tests/use-cases/get-user-from-x-frigg-headers.test.js +0 -346
  117. package/user/tests/use-cases/login-user.test.js +0 -220
  118. package/user/tests/user-password-encryption-isolation.test.js +0 -237
  119. package/user/tests/user-password-hashing.test.js +0 -235
  120. package/websocket/repositories/websocket-connection-repository.test.js +0 -227
@@ -1,178 +0,0 @@
1
- /**
2
- * CreateProcess Use Case Tests
3
- *
4
- * Tests process creation with validation and error handling.
5
- */
6
-
7
- const { CreateProcess } = require('./create-process');
8
-
9
- describe('CreateProcess', () => {
10
- let createProcessUseCase;
11
- let mockProcessRepository;
12
-
13
- beforeEach(() => {
14
- mockProcessRepository = {
15
- create: jest.fn(),
16
- };
17
- createProcessUseCase = new CreateProcess({
18
- processRepository: mockProcessRepository,
19
- });
20
- });
21
-
22
- describe('constructor', () => {
23
- it('should require processRepository', () => {
24
- expect(() => new CreateProcess({})).toThrow('processRepository is required');
25
- });
26
-
27
- it('should initialize with processRepository', () => {
28
- expect(createProcessUseCase.processRepository).toBe(mockProcessRepository);
29
- });
30
- });
31
-
32
- describe('execute', () => {
33
- const validProcessData = {
34
- userId: 'user-123',
35
- integrationId: 'integration-456',
36
- name: 'test-crm-contact-sync',
37
- type: 'CRM_SYNC',
38
- };
39
-
40
- it('should create a process with minimal required data', async () => {
41
- const mockCreatedProcess = { id: 'process-789', ...validProcessData };
42
- mockProcessRepository.create.mockResolvedValue(mockCreatedProcess);
43
-
44
- const result = await createProcessUseCase.execute(validProcessData);
45
-
46
- expect(mockProcessRepository.create).toHaveBeenCalledWith({
47
- userId: 'user-123',
48
- integrationId: 'integration-456',
49
- name: 'test-crm-contact-sync',
50
- type: 'CRM_SYNC',
51
- state: 'INITIALIZING',
52
- context: {},
53
- results: {},
54
- childProcesses: [],
55
- parentProcessId: null,
56
- });
57
- expect(result).toEqual(mockCreatedProcess);
58
- });
59
-
60
- it('should create a process with all optional data', async () => {
61
- const processDataWithOptions = {
62
- ...validProcessData,
63
- state: 'FETCHING_TOTAL',
64
- context: { syncType: 'INITIAL', totalRecords: 100 },
65
- results: { aggregateData: { totalSynced: 0 } },
66
- childProcesses: ['child-1', 'child-2'],
67
- parentProcessId: 'parent-123',
68
- };
69
-
70
- const mockCreatedProcess = { id: 'process-789', ...processDataWithOptions };
71
- mockProcessRepository.create.mockResolvedValue(mockCreatedProcess);
72
-
73
- const result = await createProcessUseCase.execute(processDataWithOptions);
74
-
75
- expect(mockProcessRepository.create).toHaveBeenCalledWith(processDataWithOptions);
76
- expect(result).toEqual(mockCreatedProcess);
77
- });
78
-
79
- it('should throw error if userId is missing', async () => {
80
- const invalidData = { integrationId: 'int-123', name: 'test', type: 'CRM_SYNC' };
81
-
82
- await expect(createProcessUseCase.execute(invalidData))
83
- .rejects.toThrow('Missing required fields for process creation: userId');
84
- });
85
-
86
- it('should throw error if integrationId is missing', async () => {
87
- const invalidData = { userId: 'user-123', name: 'test', type: 'CRM_SYNC' };
88
-
89
- await expect(createProcessUseCase.execute(invalidData))
90
- .rejects.toThrow('Missing required fields for process creation: integrationId');
91
- });
92
-
93
- it('should throw error if name is missing', async () => {
94
- const invalidData = { userId: 'user-123', integrationId: 'int-123', type: 'CRM_SYNC' };
95
-
96
- await expect(createProcessUseCase.execute(invalidData))
97
- .rejects.toThrow('Missing required fields for process creation: name');
98
- });
99
-
100
- it('should throw error if type is missing', async () => {
101
- const invalidData = { userId: 'user-123', integrationId: 'int-123', name: 'test' };
102
-
103
- await expect(createProcessUseCase.execute(invalidData))
104
- .rejects.toThrow('Missing required fields for process creation: type');
105
- });
106
-
107
- it('should throw error if userId is not a string', async () => {
108
- const invalidData = { ...validProcessData, userId: 123 };
109
-
110
- await expect(createProcessUseCase.execute(invalidData))
111
- .rejects.toThrow('userId must be a string');
112
- });
113
-
114
- it('should throw error if integrationId is not a string', async () => {
115
- const invalidData = { ...validProcessData, integrationId: 456 };
116
-
117
- await expect(createProcessUseCase.execute(invalidData))
118
- .rejects.toThrow('integrationId must be a string');
119
- });
120
-
121
- it('should throw error if name is not a string', async () => {
122
- const invalidData = { ...validProcessData, name: 789 };
123
-
124
- await expect(createProcessUseCase.execute(invalidData))
125
- .rejects.toThrow('name must be a string');
126
- });
127
-
128
- it('should throw error if type is not a string', async () => {
129
- const invalidData = { ...validProcessData, type: 999 };
130
-
131
- await expect(createProcessUseCase.execute(invalidData))
132
- .rejects.toThrow('type must be a string');
133
- });
134
-
135
- it('should throw error if state is provided but not a string', async () => {
136
- const invalidData = { ...validProcessData, state: 123 };
137
-
138
- await expect(createProcessUseCase.execute(invalidData))
139
- .rejects.toThrow('state must be a string');
140
- });
141
-
142
- it('should throw error if context is provided but not an object', async () => {
143
- const invalidData = { ...validProcessData, context: 'invalid' };
144
-
145
- await expect(createProcessUseCase.execute(invalidData))
146
- .rejects.toThrow('context must be an object');
147
- });
148
-
149
- it('should throw error if results is provided but not an object', async () => {
150
- const invalidData = { ...validProcessData, results: 'invalid' };
151
-
152
- await expect(createProcessUseCase.execute(invalidData))
153
- .rejects.toThrow('results must be an object');
154
- });
155
-
156
- it('should throw error if childProcesses is provided but not an array', async () => {
157
- const invalidData = { ...validProcessData, childProcesses: 'invalid' };
158
-
159
- await expect(createProcessUseCase.execute(invalidData))
160
- .rejects.toThrow('childProcesses must be an array');
161
- });
162
-
163
- it('should throw error if parentProcessId is provided but not a string', async () => {
164
- const invalidData = { ...validProcessData, parentProcessId: 123 };
165
-
166
- await expect(createProcessUseCase.execute(invalidData))
167
- .rejects.toThrow('parentProcessId must be a string');
168
- });
169
-
170
- it('should handle repository errors', async () => {
171
- const repositoryError = new Error('Database connection failed');
172
- mockProcessRepository.create.mockRejectedValue(repositoryError);
173
-
174
- await expect(createProcessUseCase.execute(validProcessData))
175
- .rejects.toThrow('Failed to create process: Database connection failed');
176
- });
177
- });
178
- });
@@ -1,190 +0,0 @@
1
- /**
2
- * GetProcess Use Case Tests
3
- *
4
- * Tests process retrieval with error handling.
5
- */
6
-
7
- const { GetProcess } = require('./get-process');
8
-
9
- describe('GetProcess', () => {
10
- let getProcessUseCase;
11
- let mockProcessRepository;
12
-
13
- beforeEach(() => {
14
- mockProcessRepository = {
15
- findById: jest.fn(),
16
- };
17
- getProcessUseCase = new GetProcess({
18
- processRepository: mockProcessRepository,
19
- });
20
- });
21
-
22
- describe('constructor', () => {
23
- it('should require processRepository', () => {
24
- expect(() => new GetProcess({})).toThrow('processRepository is required');
25
- });
26
-
27
- it('should initialize with processRepository', () => {
28
- expect(getProcessUseCase.processRepository).toBe(mockProcessRepository);
29
- });
30
- });
31
-
32
- describe('execute', () => {
33
- const processId = 'process-123';
34
- const mockProcess = {
35
- id: processId,
36
- userId: 'user-456',
37
- integrationId: 'integration-789',
38
- name: 'test-sync',
39
- type: 'CRM_SYNC',
40
- state: 'PROCESSING_BATCHES',
41
- context: {
42
- syncType: 'INITIAL',
43
- totalRecords: 1000,
44
- processedRecords: 500,
45
- },
46
- results: {
47
- aggregateData: {
48
- totalSynced: 480,
49
- totalFailed: 20,
50
- duration: 120000,
51
- recordsPerSecond: 4.17,
52
- },
53
- },
54
- createdAt: new Date('2024-01-01T10:00:00Z'),
55
- updatedAt: new Date('2024-01-01T10:02:00Z'),
56
- };
57
-
58
- it('should retrieve a process by ID', async () => {
59
- mockProcessRepository.findById.mockResolvedValue(mockProcess);
60
-
61
- const result = await getProcessUseCase.execute(processId);
62
-
63
- expect(mockProcessRepository.findById).toHaveBeenCalledWith(processId);
64
- expect(result).toEqual(mockProcess);
65
- });
66
-
67
- it('should return null if process not found', async () => {
68
- mockProcessRepository.findById.mockResolvedValue(null);
69
-
70
- const result = await getProcessUseCase.execute(processId);
71
-
72
- expect(mockProcessRepository.findById).toHaveBeenCalledWith(processId);
73
- expect(result).toBeNull();
74
- });
75
-
76
- it('should throw error if processId is missing', async () => {
77
- await expect(getProcessUseCase.execute(''))
78
- .rejects.toThrow('processId must be a non-empty string');
79
- });
80
-
81
- it('should throw error if processId is not a string', async () => {
82
- await expect(getProcessUseCase.execute(123))
83
- .rejects.toThrow('processId must be a non-empty string');
84
- });
85
-
86
- it('should handle repository errors', async () => {
87
- const repositoryError = new Error('Database connection failed');
88
- mockProcessRepository.findById.mockRejectedValue(repositoryError);
89
-
90
- await expect(getProcessUseCase.execute(processId))
91
- .rejects.toThrow('Failed to retrieve process: Database connection failed');
92
- });
93
- });
94
-
95
- describe('executeOrThrow', () => {
96
- const processId = 'process-123';
97
- const mockProcess = {
98
- id: processId,
99
- userId: 'user-456',
100
- integrationId: 'integration-789',
101
- name: 'test-sync',
102
- type: 'CRM_SYNC',
103
- state: 'COMPLETED',
104
- };
105
-
106
- it('should return process if found', async () => {
107
- mockProcessRepository.findById.mockResolvedValue(mockProcess);
108
-
109
- const result = await getProcessUseCase.executeOrThrow(processId);
110
-
111
- expect(result).toEqual(mockProcess);
112
- });
113
-
114
- it('should throw error if process not found', async () => {
115
- mockProcessRepository.findById.mockResolvedValue(null);
116
-
117
- await expect(getProcessUseCase.executeOrThrow(processId))
118
- .rejects.toThrow('Process not found: process-123');
119
- });
120
-
121
- it('should propagate repository errors', async () => {
122
- const repositoryError = new Error('Database connection failed');
123
- mockProcessRepository.findById.mockRejectedValue(repositoryError);
124
-
125
- await expect(getProcessUseCase.executeOrThrow(processId))
126
- .rejects.toThrow('Failed to retrieve process: Database connection failed');
127
- });
128
- });
129
-
130
- describe('executeMany', () => {
131
- const processIds = ['process-1', 'process-2', 'process-3'];
132
- const mockProcesses = [
133
- { id: 'process-1', name: 'sync-1', state: 'COMPLETED' },
134
- { id: 'process-2', name: 'sync-2', state: 'PROCESSING' },
135
- // process-3 will not be found
136
- ];
137
-
138
- it('should retrieve multiple processes', async () => {
139
- mockProcessRepository.findById
140
- .mockResolvedValueOnce(mockProcesses[0]) // process-1 found
141
- .mockResolvedValueOnce(mockProcesses[1]) // process-2 found
142
- .mockResolvedValueOnce(null); // process-3 not found
143
-
144
- const result = await getProcessUseCase.executeMany(processIds);
145
-
146
- expect(mockProcessRepository.findById).toHaveBeenCalledTimes(3);
147
- expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-1');
148
- expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-2');
149
- expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-3');
150
-
151
- // Should return only found processes
152
- expect(result).toEqual([mockProcesses[0], mockProcesses[1]]);
153
- });
154
-
155
- it('should return empty array if no processes found', async () => {
156
- mockProcessRepository.findById
157
- .mockResolvedValueOnce(null)
158
- .mockResolvedValueOnce(null)
159
- .mockResolvedValueOnce(null);
160
-
161
- const result = await getProcessUseCase.executeMany(processIds);
162
-
163
- expect(result).toEqual([]);
164
- });
165
-
166
- it('should throw error if processIds is not an array', async () => {
167
- await expect(getProcessUseCase.executeMany('not-an-array'))
168
- .rejects.toThrow('processIds must be an array');
169
- });
170
-
171
- it('should handle mixed success and failure', async () => {
172
- const repositoryError = new Error('Database error');
173
- mockProcessRepository.findById
174
- .mockResolvedValueOnce(mockProcesses[0]) // process-1 found
175
- .mockRejectedValueOnce(repositoryError) // process-2 error
176
- .mockResolvedValueOnce(null); // process-3 not found
177
-
178
- // Should propagate the repository error
179
- await expect(getProcessUseCase.executeMany(processIds))
180
- .rejects.toThrow('Failed to retrieve process: Database error');
181
- });
182
-
183
- it('should handle empty array', async () => {
184
- const result = await getProcessUseCase.executeMany([]);
185
-
186
- expect(mockProcessRepository.findById).not.toHaveBeenCalled();
187
- expect(result).toEqual([]);
188
- });
189
- });
190
- });
@@ -1,329 +0,0 @@
1
- jest.mock('../../database/config', () => ({
2
- DB_TYPE: 'mongodb',
3
- getDatabaseType: jest.fn(() => 'mongodb'),
4
- PRISMA_LOG_LEVEL: 'error,warn',
5
- PRISMA_QUERY_LOGGING: false,
6
- }));
7
-
8
- const { LoadIntegrationContextUseCase } = require('./load-integration-context');
9
- const { IntegrationBase } = require('../integration-base');
10
- const { createIntegrationRepository } = require('../repositories/integration-repository-factory');
11
- const { Module } = require('../../modules/module');
12
- const { ModuleFactory } = require('../../modules/module-factory');
13
- const { ModuleRepository } = require('../../modules/repositories/module-repository');
14
-
15
- // Mock OAuth2 API class that extends requester pattern
16
- class MockAsanaApi {
17
- constructor(params) {
18
- // Capture all injected params
19
- this.client_id = params.client_id;
20
- this.client_secret = params.client_secret;
21
- this.redirect_uri = params.redirect_uri;
22
- this.scope = params.scope;
23
- this.access_token = params.access_token;
24
- this.refresh_token = params.refresh_token;
25
- this.delegate = params.delegate;
26
- }
27
-
28
- async getFolders() {
29
- if (!this.access_token) {
30
- throw new Error('No access token');
31
- }
32
- return {
33
- folders: ['Marketing', 'Development', 'Design'],
34
- usedToken: this.access_token
35
- };
36
- }
37
-
38
- async listProjects() {
39
- return {
40
- projects: ['Q1 Launch', 'Website Redesign'],
41
- clientId: this.client_id
42
- };
43
- }
44
-
45
- getAuthorizationRequirements() {
46
- return { type: 'oauth2', url: this.redirect_uri };
47
- }
48
- }
49
-
50
- MockAsanaApi.requesterType = 'oauth2';
51
-
52
- class MockFrontifyApi {
53
- constructor(params) {
54
- this.client_id = params.client_id;
55
- this.client_secret = params.client_secret;
56
- this.redirect_uri = params.redirect_uri;
57
- this.scope = params.scope;
58
- this.access_token = params.access_token;
59
- this.refresh_token = params.refresh_token;
60
- this.domain = params.domain;
61
- }
62
-
63
- async listBrands() {
64
- return {
65
- brands: ['Main Brand', 'Sub Brand'],
66
- domain: this.domain,
67
- token: this.access_token
68
- };
69
- }
70
-
71
- async searchAssets(query) {
72
- return {
73
- query,
74
- assets: ['logo.svg', 'guidelines.pdf'],
75
- clientSecret: this.client_secret ? 'hidden' : null
76
- };
77
- }
78
-
79
- getAuthorizationRequirements() {
80
- return { type: 'oauth2', url: this.redirect_uri };
81
- }
82
- }
83
-
84
- MockFrontifyApi.requesterType = 'oauth2';
85
-
86
- // Module definitions with env variables
87
- const asanaDefinition = {
88
- moduleName: 'asana',
89
- modelName: 'Asana',
90
- API: MockAsanaApi,
91
- requiredAuthMethods: {
92
- getToken: async () => {},
93
- getEntityDetails: async () => {},
94
- getCredentialDetails: async () => {},
95
- apiPropertiesToPersist: {
96
- credential: ['access_token', 'refresh_token'],
97
- entity: [],
98
- },
99
- testAuthRequest: async () => true,
100
- },
101
- env: {
102
- client_id: 'ASANA_CLIENT_ID_FROM_ENV',
103
- client_secret: 'ASANA_SECRET_FROM_ENV',
104
- redirect_uri: 'https://app.example.com/auth/asana',
105
- scope: 'default',
106
- },
107
- };
108
-
109
- const frontifyDefinition = {
110
- moduleName: 'frontify',
111
- modelName: 'Frontify',
112
- API: MockFrontifyApi,
113
- requiredAuthMethods: {
114
- getToken: async () => {},
115
- getEntityDetails: async () => {},
116
- getCredentialDetails: async () => {},
117
- apiPropertiesToPersist: {
118
- credential: ['access_token', 'refresh_token'],
119
- entity: ['domain'],
120
- },
121
- testAuthRequest: async () => true,
122
- },
123
- env: {
124
- client_id: 'FRONTIFY_CLIENT_ID_FROM_ENV',
125
- client_secret: 'FRONTIFY_SECRET_FROM_ENV',
126
- redirect_uri: 'https://app.example.com/auth/frontify',
127
- scope: 'read write',
128
- },
129
- };
130
-
131
- // Integration class similar to AsanaIntegration
132
- class TestIntegration extends IntegrationBase {
133
- static Definition = {
134
- name: 'test-integration',
135
- version: '1.0.0',
136
- modules: {
137
- asana: {
138
- definition: asanaDefinition,
139
- },
140
- frontify: {
141
- definition: frontifyDefinition,
142
- },
143
- },
144
- };
145
-
146
- async performBusinessLogic() {
147
- // After hydration, this method can use API modules
148
- const folders = await this.asana.api.getFolders();
149
- const brands = await this.frontify.api.listBrands();
150
- return { folders, brands };
151
- }
152
- }
153
-
154
- describe('LoadIntegrationContextUseCase - Full Rounded Test', () => {
155
- it('should load integration with working API modules that have env vars and credentials', async () => {
156
- // Setup: Create entities with credentials (simulating DB records)
157
- const entities = [
158
- {
159
- id: 'entity-asana-123',
160
- moduleName: 'asana',
161
- userId: 'user-789',
162
- credential: {
163
- data: {
164
- access_token: 'asana_access_token_xyz',
165
- refresh_token: 'asana_refresh_token_abc',
166
- },
167
- },
168
- },
169
- {
170
- id: 'entity-frontify-456',
171
- moduleName: 'frontify',
172
- userId: 'user-789',
173
- domain: 'customer.frontify.com',
174
- credential: {
175
- data: {
176
- access_token: 'frontify_access_token_uvw',
177
- refresh_token: 'frontify_refresh_token_def',
178
- },
179
- },
180
- },
181
- ];
182
-
183
- // Mock repositories
184
- const moduleRepository = {
185
- findEntitiesByIds: jest.fn().mockResolvedValue(entities),
186
- findEntityById: jest.fn().mockImplementation((id) =>
187
- Promise.resolve(entities.find(e => e.id === id))
188
- ),
189
- };
190
-
191
- // Create module factory with definitions
192
- const moduleFactory = new ModuleFactory({
193
- moduleRepository,
194
- moduleDefinitions: [asanaDefinition, frontifyDefinition],
195
- });
196
-
197
- // Create the use case
198
- const useCase = new LoadIntegrationContextUseCase({
199
- integrationRepository: createIntegrationRepository(),
200
- moduleRepository,
201
- moduleFactory,
202
- });
203
-
204
- // Execute: Load integration context
205
- const integrationRecord = {
206
- id: 'integration-999',
207
- userId: 'user-789',
208
- entitiesIds: ['entity-asana-123', 'entity-frontify-456'],
209
- status: 'active',
210
- config: { someConfig: true },
211
- };
212
-
213
- const context = await useCase.execute({ integrationRecord });
214
-
215
- // Verify: Context has modules
216
- expect(context.modules).toHaveLength(2);
217
-
218
- // Create integration instance and hydrate it
219
- const integration = new TestIntegration();
220
- integration.setIntegrationRecord(context);
221
-
222
- // Verify: Integration has modules attached
223
- expect(integration.asana).toBeDefined();
224
- expect(integration.frontify).toBeDefined();
225
- expect(integration.modules.asana).toBe(integration.asana);
226
- expect(integration.modules.frontify).toBe(integration.frontify);
227
-
228
- // CRITICAL TEST: Verify API instances have env vars from definition
229
- expect(integration.asana.api.client_id).toBe('ASANA_CLIENT_ID_FROM_ENV');
230
- expect(integration.asana.api.client_secret).toBe('ASANA_SECRET_FROM_ENV');
231
- expect(integration.asana.api.redirect_uri).toBe('https://app.example.com/auth/asana');
232
- expect(integration.asana.api.scope).toBe('default');
233
-
234
- expect(integration.frontify.api.client_id).toBe('FRONTIFY_CLIENT_ID_FROM_ENV');
235
- expect(integration.frontify.api.client_secret).toBe('FRONTIFY_SECRET_FROM_ENV');
236
- expect(integration.frontify.api.redirect_uri).toBe('https://app.example.com/auth/frontify');
237
- expect(integration.frontify.api.scope).toBe('read write');
238
-
239
- // CRITICAL TEST: Verify API instances have credentials from entities
240
- expect(integration.asana.api.access_token).toBe('asana_access_token_xyz');
241
- expect(integration.asana.api.refresh_token).toBe('asana_refresh_token_abc');
242
-
243
- expect(integration.frontify.api.access_token).toBe('frontify_access_token_uvw');
244
- expect(integration.frontify.api.refresh_token).toBe('frontify_refresh_token_def');
245
- expect(integration.frontify.api.domain).toBe('customer.frontify.com');
246
-
247
- // CRITICAL TEST: Can call API methods successfully
248
- const folders = await integration.asana.api.getFolders();
249
- expect(folders.folders).toEqual(['Marketing', 'Development', 'Design']);
250
- expect(folders.usedToken).toBe('asana_access_token_xyz');
251
-
252
- const projects = await integration.asana.api.listProjects();
253
- expect(projects.projects).toEqual(['Q1 Launch', 'Website Redesign']);
254
- expect(projects.clientId).toBe('ASANA_CLIENT_ID_FROM_ENV');
255
-
256
- const brands = await integration.frontify.api.listBrands();
257
- expect(brands.brands).toEqual(['Main Brand', 'Sub Brand']);
258
- expect(brands.domain).toBe('customer.frontify.com');
259
- expect(brands.token).toBe('frontify_access_token_uvw');
260
-
261
- const assets = await integration.frontify.api.searchAssets('logo');
262
- expect(assets.query).toBe('logo');
263
- expect(assets.assets).toEqual(['logo.svg', 'guidelines.pdf']);
264
- expect(assets.clientSecret).toBe('hidden'); // Verifies secret exists
265
-
266
- // CRITICAL TEST: Business logic methods can use hydrated APIs
267
- const businessResult = await integration.performBusinessLogic();
268
- expect(businessResult.folders.folders).toEqual(['Marketing', 'Development', 'Design']);
269
- expect(businessResult.brands.brands).toEqual(['Main Brand', 'Sub Brand']);
270
-
271
- // Verify the complete chain: env → Module → API → Integration
272
- console.log('\n✅ Full Integration Test Results:');
273
- console.log(' ENV vars injected: ✓');
274
- console.log(' Credentials injected: ✓');
275
- console.log(' API methods callable: ✓');
276
- console.log(' Business logic works: ✓');
277
- });
278
-
279
- it('should handle missing credentials gracefully', async () => {
280
- // Entity without credentials
281
- const entities = [
282
- {
283
- id: 'entity-no-creds',
284
- moduleName: 'asana',
285
- userId: 'user-123',
286
- credential: {
287
- data: {
288
- // Empty credential data - no access_token
289
- },
290
- },
291
- },
292
- ];
293
-
294
- const moduleRepository = {
295
- findEntitiesByIds: jest.fn().mockResolvedValue(entities),
296
- findEntityById: jest.fn().mockResolvedValue(entities[0]),
297
- };
298
-
299
- const moduleFactory = new ModuleFactory({
300
- moduleRepository,
301
- moduleDefinitions: [asanaDefinition],
302
- });
303
-
304
- const useCase = new LoadIntegrationContextUseCase({
305
- integrationRepository: createIntegrationRepository(),
306
- moduleRepository,
307
- moduleFactory,
308
- });
309
-
310
- const context = await useCase.execute({
311
- integrationRecord: {
312
- id: 'integration-1',
313
- userId: 'user-123',
314
- entitiesIds: ['entity-no-creds'],
315
- },
316
- });
317
-
318
- const integration = new TestIntegration();
319
- integration.setIntegrationRecord(context);
320
-
321
- // Should have module with env vars but no credentials
322
- expect(integration.asana).toBeDefined();
323
- expect(integration.asana.api.client_id).toBe('ASANA_CLIENT_ID_FROM_ENV');
324
- expect(integration.asana.api.access_token).toBeUndefined();
325
-
326
- // API method should fail without token
327
- await expect(integration.asana.api.getFolders()).rejects.toThrow('No access token');
328
- });
329
- });