@friggframework/core 2.0.0--canary.395.a6dcc5a.0 → 2.0.0--canary.395.de6bcdf.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.
@@ -0,0 +1,314 @@
1
+ const { LoadIntegrationContextUseCase } = require('./load-integration-context');
2
+ const { IntegrationBase } = require('../integration-base');
3
+ const { Module } = require('../../modules/module');
4
+ const { ModuleFactory } = require('../../modules/module-factory');
5
+ const { ModuleRepository } = require('../../modules/module-repository');
6
+
7
+ // Mock OAuth2 API class that extends requester pattern
8
+ class MockAsanaApi {
9
+ constructor(params) {
10
+ // Capture all injected params
11
+ this.client_id = params.client_id;
12
+ this.client_secret = params.client_secret;
13
+ this.redirect_uri = params.redirect_uri;
14
+ this.scope = params.scope;
15
+ this.access_token = params.access_token;
16
+ this.refresh_token = params.refresh_token;
17
+ this.delegate = params.delegate;
18
+ }
19
+
20
+ async getFolders() {
21
+ if (!this.access_token) {
22
+ throw new Error('No access token');
23
+ }
24
+ return {
25
+ folders: ['Marketing', 'Development', 'Design'],
26
+ usedToken: this.access_token
27
+ };
28
+ }
29
+
30
+ async listProjects() {
31
+ return {
32
+ projects: ['Q1 Launch', 'Website Redesign'],
33
+ clientId: this.client_id
34
+ };
35
+ }
36
+
37
+ getAuthorizationRequirements() {
38
+ return { type: 'oauth2', url: this.redirect_uri };
39
+ }
40
+ }
41
+
42
+ MockAsanaApi.requesterType = 'oauth2';
43
+
44
+ class MockFrontifyApi {
45
+ constructor(params) {
46
+ this.client_id = params.client_id;
47
+ this.client_secret = params.client_secret;
48
+ this.redirect_uri = params.redirect_uri;
49
+ this.scope = params.scope;
50
+ this.access_token = params.access_token;
51
+ this.refresh_token = params.refresh_token;
52
+ this.domain = params.domain;
53
+ }
54
+
55
+ async listBrands() {
56
+ return {
57
+ brands: ['Main Brand', 'Sub Brand'],
58
+ domain: this.domain,
59
+ token: this.access_token
60
+ };
61
+ }
62
+
63
+ async searchAssets(query) {
64
+ return {
65
+ query,
66
+ assets: ['logo.svg', 'guidelines.pdf'],
67
+ clientSecret: this.client_secret ? 'hidden' : null
68
+ };
69
+ }
70
+
71
+ getAuthorizationRequirements() {
72
+ return { type: 'oauth2', url: this.redirect_uri };
73
+ }
74
+ }
75
+
76
+ MockFrontifyApi.requesterType = 'oauth2';
77
+
78
+ // Module definitions with env variables
79
+ const asanaDefinition = {
80
+ moduleName: 'asana',
81
+ modelName: 'Asana',
82
+ API: MockAsanaApi,
83
+ requiredAuthMethods: {
84
+ getToken: async () => {},
85
+ getEntityDetails: async () => {},
86
+ getCredentialDetails: async () => {},
87
+ apiPropertiesToPersist: {
88
+ credential: ['access_token', 'refresh_token'],
89
+ entity: [],
90
+ },
91
+ testAuthRequest: async () => true,
92
+ },
93
+ env: {
94
+ client_id: 'ASANA_CLIENT_ID_FROM_ENV',
95
+ client_secret: 'ASANA_SECRET_FROM_ENV',
96
+ redirect_uri: 'https://app.example.com/auth/asana',
97
+ scope: 'default',
98
+ },
99
+ };
100
+
101
+ const frontifyDefinition = {
102
+ moduleName: 'frontify',
103
+ modelName: 'Frontify',
104
+ API: MockFrontifyApi,
105
+ requiredAuthMethods: {
106
+ getToken: async () => {},
107
+ getEntityDetails: async () => {},
108
+ getCredentialDetails: async () => {},
109
+ apiPropertiesToPersist: {
110
+ credential: ['access_token', 'refresh_token'],
111
+ entity: ['domain'],
112
+ },
113
+ testAuthRequest: async () => true,
114
+ },
115
+ env: {
116
+ client_id: 'FRONTIFY_CLIENT_ID_FROM_ENV',
117
+ client_secret: 'FRONTIFY_SECRET_FROM_ENV',
118
+ redirect_uri: 'https://app.example.com/auth/frontify',
119
+ scope: 'read write',
120
+ },
121
+ };
122
+
123
+ // Integration class similar to AsanaIntegration
124
+ class TestIntegration extends IntegrationBase {
125
+ static Definition = {
126
+ name: 'test-integration',
127
+ version: '1.0.0',
128
+ modules: {
129
+ asana: {
130
+ definition: asanaDefinition,
131
+ },
132
+ frontify: {
133
+ definition: frontifyDefinition,
134
+ },
135
+ },
136
+ };
137
+
138
+ async performBusinessLogic() {
139
+ // After hydration, this method can use API modules
140
+ const folders = await this.asana.api.getFolders();
141
+ const brands = await this.frontify.api.listBrands();
142
+ return { folders, brands };
143
+ }
144
+ }
145
+
146
+ describe('LoadIntegrationContextUseCase - Full Rounded Test', () => {
147
+ it('should load integration with working API modules that have env vars and credentials', async () => {
148
+ // Setup: Create entities with credentials (simulating DB records)
149
+ const entities = [
150
+ {
151
+ id: 'entity-asana-123',
152
+ moduleName: 'asana',
153
+ userId: 'user-789',
154
+ credential: {
155
+ access_token: 'asana_access_token_xyz',
156
+ refresh_token: 'asana_refresh_token_abc',
157
+ },
158
+ },
159
+ {
160
+ id: 'entity-frontify-456',
161
+ moduleName: 'frontify',
162
+ userId: 'user-789',
163
+ domain: 'customer.frontify.com',
164
+ credential: {
165
+ access_token: 'frontify_access_token_uvw',
166
+ refresh_token: 'frontify_refresh_token_def',
167
+ },
168
+ },
169
+ ];
170
+
171
+ // Mock repositories
172
+ const moduleRepository = {
173
+ findEntitiesByIds: jest.fn().mockResolvedValue(entities),
174
+ findEntityById: jest.fn().mockImplementation((id) =>
175
+ Promise.resolve(entities.find(e => e.id === id))
176
+ ),
177
+ };
178
+
179
+ // Create module factory with definitions
180
+ const moduleFactory = new ModuleFactory({
181
+ moduleRepository,
182
+ moduleDefinitions: [asanaDefinition, frontifyDefinition],
183
+ });
184
+
185
+ // Create the use case
186
+ const useCase = new LoadIntegrationContextUseCase({
187
+ integrationClass: TestIntegration,
188
+ integrationRepository: {},
189
+ moduleRepository,
190
+ moduleFactory,
191
+ });
192
+
193
+ // Execute: Load integration context
194
+ const integrationRecord = {
195
+ id: 'integration-999',
196
+ userId: 'user-789',
197
+ entitiesIds: ['entity-asana-123', 'entity-frontify-456'],
198
+ status: 'active',
199
+ config: { someConfig: true },
200
+ };
201
+
202
+ const context = await useCase.execute({ integrationRecord });
203
+
204
+ // Verify: Context has modules
205
+ expect(context.modules).toHaveLength(2);
206
+
207
+ // Create integration instance and hydrate it
208
+ const integration = new TestIntegration();
209
+ integration.setIntegrationRecord(context);
210
+
211
+ // Verify: Integration has modules attached
212
+ expect(integration.asana).toBeDefined();
213
+ expect(integration.frontify).toBeDefined();
214
+ expect(integration.modules.asana).toBe(integration.asana);
215
+ expect(integration.modules.frontify).toBe(integration.frontify);
216
+
217
+ // CRITICAL TEST: Verify API instances have env vars from definition
218
+ expect(integration.asana.api.client_id).toBe('ASANA_CLIENT_ID_FROM_ENV');
219
+ expect(integration.asana.api.client_secret).toBe('ASANA_SECRET_FROM_ENV');
220
+ expect(integration.asana.api.redirect_uri).toBe('https://app.example.com/auth/asana');
221
+ expect(integration.asana.api.scope).toBe('default');
222
+
223
+ expect(integration.frontify.api.client_id).toBe('FRONTIFY_CLIENT_ID_FROM_ENV');
224
+ expect(integration.frontify.api.client_secret).toBe('FRONTIFY_SECRET_FROM_ENV');
225
+ expect(integration.frontify.api.redirect_uri).toBe('https://app.example.com/auth/frontify');
226
+ expect(integration.frontify.api.scope).toBe('read write');
227
+
228
+ // CRITICAL TEST: Verify API instances have credentials from entities
229
+ expect(integration.asana.api.access_token).toBe('asana_access_token_xyz');
230
+ expect(integration.asana.api.refresh_token).toBe('asana_refresh_token_abc');
231
+
232
+ expect(integration.frontify.api.access_token).toBe('frontify_access_token_uvw');
233
+ expect(integration.frontify.api.refresh_token).toBe('frontify_refresh_token_def');
234
+ expect(integration.frontify.api.domain).toBe('customer.frontify.com');
235
+
236
+ // CRITICAL TEST: Can call API methods successfully
237
+ const folders = await integration.asana.api.getFolders();
238
+ expect(folders.folders).toEqual(['Marketing', 'Development', 'Design']);
239
+ expect(folders.usedToken).toBe('asana_access_token_xyz');
240
+
241
+ const projects = await integration.asana.api.listProjects();
242
+ expect(projects.projects).toEqual(['Q1 Launch', 'Website Redesign']);
243
+ expect(projects.clientId).toBe('ASANA_CLIENT_ID_FROM_ENV');
244
+
245
+ const brands = await integration.frontify.api.listBrands();
246
+ expect(brands.brands).toEqual(['Main Brand', 'Sub Brand']);
247
+ expect(brands.domain).toBe('customer.frontify.com');
248
+ expect(brands.token).toBe('frontify_access_token_uvw');
249
+
250
+ const assets = await integration.frontify.api.searchAssets('logo');
251
+ expect(assets.query).toBe('logo');
252
+ expect(assets.assets).toEqual(['logo.svg', 'guidelines.pdf']);
253
+ expect(assets.clientSecret).toBe('hidden'); // Verifies secret exists
254
+
255
+ // CRITICAL TEST: Business logic methods can use hydrated APIs
256
+ const businessResult = await integration.performBusinessLogic();
257
+ expect(businessResult.folders.folders).toEqual(['Marketing', 'Development', 'Design']);
258
+ expect(businessResult.brands.brands).toEqual(['Main Brand', 'Sub Brand']);
259
+
260
+ // Verify the complete chain: env → Module → API → Integration
261
+ console.log('\n✅ Full Integration Test Results:');
262
+ console.log(' ENV vars injected: ✓');
263
+ console.log(' Credentials injected: ✓');
264
+ console.log(' API methods callable: ✓');
265
+ console.log(' Business logic works: ✓');
266
+ });
267
+
268
+ it('should handle missing credentials gracefully', async () => {
269
+ // Entity without credentials
270
+ const entities = [
271
+ {
272
+ id: 'entity-no-creds',
273
+ moduleName: 'asana',
274
+ userId: 'user-123',
275
+ // No credential property
276
+ },
277
+ ];
278
+
279
+ const moduleRepository = {
280
+ findEntitiesByIds: jest.fn().mockResolvedValue(entities),
281
+ findEntityById: jest.fn().mockResolvedValue(entities[0]),
282
+ };
283
+
284
+ const moduleFactory = new ModuleFactory({
285
+ moduleRepository,
286
+ moduleDefinitions: [asanaDefinition],
287
+ });
288
+
289
+ const useCase = new LoadIntegrationContextUseCase({
290
+ integrationClass: TestIntegration,
291
+ moduleRepository,
292
+ moduleFactory,
293
+ });
294
+
295
+ const context = await useCase.execute({
296
+ integrationRecord: {
297
+ id: 'integration-1',
298
+ userId: 'user-123',
299
+ entitiesIds: ['entity-no-creds'],
300
+ },
301
+ });
302
+
303
+ const integration = new TestIntegration();
304
+ integration.setIntegrationRecord(context);
305
+
306
+ // Should have module with env vars but no credentials
307
+ expect(integration.asana).toBeDefined();
308
+ expect(integration.asana.api.client_id).toBe('ASANA_CLIENT_ID_FROM_ENV');
309
+ expect(integration.asana.api.access_token).toBeUndefined();
310
+
311
+ // API method should fail without token
312
+ await expect(integration.asana.api.getFolders()).rejects.toThrow('No access token');
313
+ });
314
+ });
@@ -0,0 +1,77 @@
1
+ const { IntegrationRepository } = require('../integration-repository');
2
+ const { ModuleRepository } = require('../../modules/module-repository');
3
+ const { ModuleFactory } = require('../../modules/module-factory');
4
+ const { getModulesDefinitionFromIntegrationClasses } = require('../utils/map-integration-dto');
5
+
6
+ class LoadIntegrationContextUseCase {
7
+ constructor({
8
+ integrationClass,
9
+ integrationRepository,
10
+ moduleRepository,
11
+ moduleFactory,
12
+ }) {
13
+ if (!integrationClass) {
14
+ throw new Error('integrationClass is required');
15
+ }
16
+
17
+ this.integrationClass = integrationClass;
18
+ this.integrationRepository = integrationRepository || new IntegrationRepository();
19
+ this.moduleRepository = moduleRepository || new ModuleRepository();
20
+
21
+ const moduleDefinitions = getModulesDefinitionFromIntegrationClasses([
22
+ integrationClass,
23
+ ]);
24
+
25
+ this.moduleFactory =
26
+ moduleFactory ||
27
+ new ModuleFactory({
28
+ moduleRepository: this.moduleRepository,
29
+ moduleDefinitions,
30
+ });
31
+ }
32
+
33
+ async execute({ integrationId, integrationRecord }) {
34
+ const record = integrationRecord
35
+ ? integrationRecord
36
+ : await this.integrationRepository.findIntegrationById(integrationId);
37
+
38
+ if (!record) {
39
+ const error = new Error('Integration record not found');
40
+ error.code = 'INTEGRATION_RECORD_NOT_FOUND';
41
+ throw error;
42
+ }
43
+
44
+ if (!Array.isArray(record.entitiesIds) || record.entitiesIds.length === 0) {
45
+ return {
46
+ record: {
47
+ ...record,
48
+ entities: [],
49
+ },
50
+ modules: [],
51
+ };
52
+ }
53
+
54
+ const entities = await this.moduleRepository.findEntitiesByIds(
55
+ record.entitiesIds
56
+ );
57
+
58
+ const modules = [];
59
+ for (const entity of entities) {
60
+ const moduleInstance = await this.moduleFactory.getModuleInstance(
61
+ entity.id,
62
+ record.userId
63
+ );
64
+ modules.push(moduleInstance);
65
+ }
66
+
67
+ return {
68
+ record: {
69
+ ...record,
70
+ entities,
71
+ },
72
+ modules,
73
+ };
74
+ }
75
+ }
76
+
77
+ module.exports = { LoadIntegrationContextUseCase };
@@ -0,0 +1,114 @@
1
+ const { LoadIntegrationContextUseCase } = require('./load-integration-context');
2
+
3
+ class FakeIntegration {}
4
+ FakeIntegration.Definition = {
5
+ name: 'fake',
6
+ modules: {},
7
+ };
8
+
9
+ describe('LoadIntegrationContextUseCase', () => {
10
+ it('throws when neither integrationId nor integrationRecord resolve to a record', async () => {
11
+ const integrationRepository = {
12
+ findIntegrationById: jest.fn().mockResolvedValue(null),
13
+ };
14
+
15
+ const useCase = new LoadIntegrationContextUseCase({
16
+ integrationClass: FakeIntegration,
17
+ integrationRepository,
18
+ moduleRepository: { findEntitiesByIds: jest.fn() },
19
+ moduleFactory: { getModuleInstance: jest.fn() },
20
+ });
21
+
22
+ await expect(
23
+ useCase.execute({ integrationId: 'missing-id' })
24
+ ).rejects.toMatchObject({
25
+ message: 'Integration record not found',
26
+ code: 'INTEGRATION_RECORD_NOT_FOUND',
27
+ });
28
+ });
29
+
30
+ it('returns record with empty entities/modules when no entity ids provided', async () => {
31
+ const integrationRecord = {
32
+ id: 'integration-1',
33
+ userId: 'user-1',
34
+ entitiesIds: [],
35
+ };
36
+
37
+ const moduleRepository = { findEntitiesByIds: jest.fn() };
38
+ const moduleFactory = { getModuleInstance: jest.fn() };
39
+
40
+ const useCase = new LoadIntegrationContextUseCase({
41
+ integrationClass: FakeIntegration,
42
+ integrationRepository: {},
43
+ moduleRepository,
44
+ moduleFactory,
45
+ });
46
+
47
+ const result = await useCase.execute({ integrationRecord });
48
+
49
+ expect(result).toEqual({
50
+ record: {
51
+ ...integrationRecord,
52
+ entities: [],
53
+ },
54
+ modules: [],
55
+ });
56
+ expect(moduleRepository.findEntitiesByIds).not.toHaveBeenCalled();
57
+ expect(moduleFactory.getModuleInstance).not.toHaveBeenCalled();
58
+ });
59
+
60
+ it('hydrates modules and entities when entity ids are provided', async () => {
61
+ const integrationRecord = {
62
+ id: 'integration-2',
63
+ userId: 'user-2',
64
+ entitiesIds: ['entity-1', 'entity-2'],
65
+ };
66
+
67
+ const entities = [
68
+ { id: 'entity-1', name: 'First Entity' },
69
+ { id: 'entity-2', name: 'Second Entity' },
70
+ ];
71
+
72
+ const modules = [{ name: 'module-1' }, { name: 'module-2' }];
73
+
74
+ const moduleRepository = {
75
+ findEntitiesByIds: jest.fn().mockResolvedValue(entities),
76
+ };
77
+ const moduleFactory = {
78
+ getModuleInstance: jest
79
+ .fn()
80
+ .mockResolvedValueOnce(modules[0])
81
+ .mockResolvedValueOnce(modules[1]),
82
+ };
83
+
84
+ const useCase = new LoadIntegrationContextUseCase({
85
+ integrationClass: FakeIntegration,
86
+ integrationRepository: {},
87
+ moduleRepository,
88
+ moduleFactory,
89
+ });
90
+
91
+ const result = await useCase.execute({ integrationRecord });
92
+
93
+ expect(moduleRepository.findEntitiesByIds).toHaveBeenCalledWith(
94
+ integrationRecord.entitiesIds
95
+ );
96
+ expect(moduleFactory.getModuleInstance).toHaveBeenNthCalledWith(
97
+ 1,
98
+ 'entity-1',
99
+ integrationRecord.userId
100
+ );
101
+ expect(moduleFactory.getModuleInstance).toHaveBeenNthCalledWith(
102
+ 2,
103
+ 'entity-2',
104
+ integrationRecord.userId
105
+ );
106
+ expect(result).toEqual({
107
+ record: {
108
+ ...integrationRecord,
109
+ entities,
110
+ },
111
+ modules,
112
+ });
113
+ });
114
+ });
@@ -0,0 +1,3 @@
1
+ module.exports = async function noopGlobalSetup() {
2
+ // No global setup required for unit tests.
3
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = async function noopGlobalTeardown() {
2
+ // No global teardown required for unit tests.
3
+ };
package/modules/index.js CHANGED
@@ -5,6 +5,8 @@ const { BasicAuthRequester } = require('./requester/basic');
5
5
  const { OAuth2Requester } = require('./requester/oauth-2');
6
6
  const { Requester } = require('./requester/requester');
7
7
  const { ModuleConstants } = require('./ModuleConstants');
8
+ const { ModuleFactory } = require('./module-factory');
9
+ const { ModuleRepository } = require('./module-repository');
8
10
 
9
11
  module.exports = {
10
12
  Credential,
@@ -14,4 +16,6 @@ module.exports = {
14
16
  OAuth2Requester,
15
17
  Requester,
16
18
  ModuleConstants,
19
+ ModuleFactory,
20
+ ModuleRepository,
17
21
  };
@@ -39,7 +39,7 @@ class ModuleFactory {
39
39
 
40
40
  if (!moduleDefinition) {
41
41
  throw new Error(
42
- `Module definition not found for entity type: ${entityType}`
42
+ `Module definition not found for module: ${moduleName}`
43
43
  );
44
44
  }
45
45