@friggframework/core 2.0.0--canary.667.f74cf3b.0 → 2.0.0--canary.710.7cfcf12.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 (48) hide show
  1. package/CLAUDE.md +41 -1
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/database/documentdb-encryption-service.js +2 -33
  6. package/database/documentdb-utils.js +4 -1
  7. package/database/encryption/README.md +3 -3
  8. package/database/encryption/ciphertext-format.js +24 -0
  9. package/database/encryption/encryption-schema-registry.js +109 -29
  10. package/database/encryption/field-encryption-service.js +13 -16
  11. package/database/prisma.js +10 -1
  12. package/errors/index.js +4 -0
  13. package/errors/mapping-already-exists-error.js +14 -0
  14. package/handlers/WEBHOOKS.md +29 -0
  15. package/index.js +2 -0
  16. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
  17. package/integrations/integration-base.js +29 -0
  18. package/integrations/integration-router.js +22 -18
  19. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  20. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  21. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  22. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  23. package/integrations/repositories/integration-mapping-repository.js +29 -0
  24. package/integrations/repositories/integration-repository-documentdb.js +32 -0
  25. package/integrations/repositories/integration-repository-interface.js +30 -0
  26. package/integrations/repositories/integration-repository-mongo.js +53 -1
  27. package/integrations/repositories/integration-repository-postgres.js +58 -0
  28. package/integrations/repositories/process-repository-mongo.js +1 -1
  29. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  30. package/integrations/use-cases/create-integration.js +57 -19
  31. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  32. package/integrations/utils/assert-entity-ids-input.js +42 -0
  33. package/jest-setup.js +13 -2
  34. package/jest-teardown.js +5 -2
  35. package/jest.config.js +4 -0
  36. package/jest.db.config.js +23 -0
  37. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  38. package/modules/use-cases/get-module.js +8 -29
  39. package/modules/use-cases/refresh-entity-options.js +5 -7
  40. package/modules/use-cases/test-module-auth.js +5 -7
  41. package/modules/utils/map-module-dto.js +5 -3
  42. package/modules/utils/to-credential-id.js +14 -0
  43. package/package.json +7 -5
  44. package/queues/queuer-util.js +6 -5
  45. package/user/tests/doubles/test-user-repository.js +1 -1
  46. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  47. package/modules/use-cases/create-entity-from-credential.js +0 -105
  48. package/modules/utils/find-module-definition.js +0 -23
@@ -1,3 +1,5 @@
1
+ const { isEncryptedEnvelope } = require('./ciphertext-format');
2
+
1
3
  /**
2
4
  * Field Encryption Service
3
5
  *
@@ -147,12 +149,7 @@ class FieldEncryptionService {
147
149
  }
148
150
 
149
151
  _isEncrypted(value) {
150
- if (typeof value !== 'string') {
151
- return false;
152
- }
153
-
154
- const parts = value.split(':');
155
- return parts.length >= 4;
152
+ return isEncryptedEnvelope(value);
156
153
  }
157
154
 
158
155
  _getNestedValue(obj, path) {
@@ -218,22 +215,22 @@ class FieldEncryptionService {
218
215
  }
219
216
 
220
217
  /**
221
- * Serialize a value for encryption
222
- * Objects/arrays are JSON stringified, primitives are converted to strings
218
+ * Serialize a value for encryption.
219
+ * Every value is JSON-encoded, strings included, so the type survives
220
+ * the round trip: '123456' is stored as "\"123456\"" and reads back as a
221
+ * string, 1234 reads back as a number.
223
222
  * @private
224
223
  */
225
224
  _serializeForEncryption(value) {
226
- if (typeof value === 'object' && value !== null) {
227
- // JSON.stringify for objects and arrays
228
- return JSON.stringify(value);
229
- }
230
- // For primitives (string, number, boolean), convert to string
231
- return String(value);
225
+ return JSON.stringify(value);
232
226
  }
233
227
 
234
228
  /**
235
- * Deserialize a value after decryption
236
- * Attempts to parse as JSON, returns string if parsing fails
229
+ * Deserialize a value after decryption.
230
+ * Parses the JSON written by _serializeForEncryption. Values encrypted by
231
+ * earlier versions stored strings raw: those that aren't valid JSON come
232
+ * back unchanged; a raw legacy string that is also valid JSON (e.g.
233
+ * '123456') still parses as it always did.
237
234
  * @private
238
235
  */
239
236
  _deserializeAfterDecryption(value) {
@@ -1,7 +1,10 @@
1
1
  const {
2
2
  createEncryptionExtension,
3
3
  } = require('./encryption/prisma-encryption-extension');
4
- const { loadCustomEncryptionSchema } = require('./encryption/encryption-schema-registry');
4
+ const {
5
+ loadCustomEncryptionSchema,
6
+ EncryptionSchemaError,
7
+ } = require('./encryption/encryption-schema-registry');
5
8
  const { logger } = require('./encryption/logger');
6
9
  const { Cryptor } = require('../encrypt/Cryptor');
7
10
  const config = require('./config');
@@ -125,6 +128,12 @@ const prismaClientSingleton = () => {
125
128
  `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
126
129
  );
127
130
  } catch (error) {
131
+ // An invalid encryption configuration must fail startup: carrying
132
+ // on without the extension would write encrypted fields in
133
+ // plaintext.
134
+ if (error instanceof EncryptionSchemaError) {
135
+ throw error;
136
+ }
128
137
  logger.error(
129
138
  'Failed to initialize encryption extension:',
130
139
  error
package/errors/index.js CHANGED
@@ -6,6 +6,9 @@ const {
6
6
  ParameterTypeError,
7
7
  } = require('./validation-errors');
8
8
  const { ClientSafeError } = require('./client-safe-error');
9
+ const {
10
+ MappingAlreadyExistsError,
11
+ } = require('./mapping-already-exists-error');
9
12
 
10
13
  module.exports = {
11
14
  BaseError,
@@ -14,4 +17,5 @@ module.exports = {
14
17
  RequiredPropertyError,
15
18
  ParameterTypeError,
16
19
  ClientSafeError,
20
+ MappingAlreadyExistsError,
17
21
  };
@@ -0,0 +1,14 @@
1
+ const { BaseError } = require('./base-error');
2
+
3
+ class MappingAlreadyExistsError extends BaseError {
4
+ constructor(integrationId, sourceId, ...errorOptions) {
5
+ super(
6
+ `Mapping already exists for integration ${integrationId} and sourceId ${sourceId}`,
7
+ ...errorOptions
8
+ );
9
+ this.integrationId = integrationId;
10
+ this.sourceId = sourceId;
11
+ }
12
+ }
13
+
14
+ module.exports = { MappingAlreadyExistsError };
@@ -483,6 +483,35 @@ async onWebhook({ data }) {
483
483
  }
484
484
  ```
485
485
 
486
+ `getMapping` followed by `upsertMapping` is not atomic. To claim an event so only one
487
+ concurrent worker proceeds, use the insert-only `createMapping`, which throws
488
+ `MappingAlreadyExistsError` (exported from `@friggframework/core`) when the
489
+ `sourceId` is already taken. `deleteMapping(sourceId)` releases the claim and is a
490
+ no-op when nothing exists.
491
+
492
+ ```javascript
493
+ const { MappingAlreadyExistsError } = require('@friggframework/core');
494
+
495
+ async onWebhook({ data }) {
496
+ const claimId = `claim:${data.body.id}`;
497
+ try {
498
+ await this.createMapping(claimId, { claimedAt: new Date() });
499
+ } catch (error) {
500
+ if (error instanceof MappingAlreadyExistsError) {
501
+ return { processed: false, duplicate: true };
502
+ }
503
+ throw error;
504
+ }
505
+
506
+ try {
507
+ await this.processEvent(data.body);
508
+ } catch (error) {
509
+ await this.deleteMapping(claimId);
510
+ throw error;
511
+ }
512
+ }
513
+ ```
514
+
486
515
  ### 4. Error Handling
487
516
  ```javascript
488
517
  async onWebhook({ data }) {
package/index.js CHANGED
@@ -57,6 +57,7 @@ const {
57
57
  HaltError,
58
58
  RequiredPropertyError,
59
59
  ParameterTypeError,
60
+ MappingAlreadyExistsError,
60
61
  } = require('./errors/index');
61
62
  const {
62
63
  IntegrationBase,
@@ -144,6 +145,7 @@ module.exports = {
144
145
  HaltError,
145
146
  RequiredPropertyError,
146
147
  ParameterTypeError,
148
+ MappingAlreadyExistsError,
147
149
 
148
150
  // integrations
149
151
  IntegrationBase,
@@ -11,19 +11,65 @@
11
11
  * This adapter implements SchedulerServiceInterface for AWS EventBridge Scheduler.
12
12
  */
13
13
 
14
- const {
15
- SchedulerClient,
16
- CreateScheduleCommand,
17
- DeleteScheduleCommand,
18
- GetScheduleCommand,
19
- ResourceNotFoundException,
20
- } = require('@aws-sdk/client-scheduler');
21
-
22
14
  const { SchedulerServiceInterface } = require('./scheduler-service-interface');
23
15
 
16
+ const SCHEDULER_SDK = '@aws-sdk/client-scheduler';
17
+
18
+ /**
19
+ * Lazily load the AWS EventBridge Scheduler SDK.
20
+ *
21
+ * Requiring `@aws-sdk/client-scheduler` at module top level would put the AWS
22
+ * SDK on the load path of every consumer of `@friggframework/core`, including
23
+ * those using the mock scheduler or no scheduler at all. Loading it here, on
24
+ * construction of the EventBridge adapter, keeps it out of the module-load
25
+ * path. The adapter calls it exactly once, in its constructor, and keeps the
26
+ * classes its methods need on the instance.
27
+ *
28
+ * Only a MODULE_NOT_FOUND for the scheduler SDK itself is rewritten into an
29
+ * actionable message; any other failure (including a missing transitive
30
+ * dependency) is rethrown unchanged so the real cause is not masked.
31
+ *
32
+ * @returns {object} The relevant exports from `@aws-sdk/client-scheduler`.
33
+ */
34
+ function loadSchedulerSdk() {
35
+ try {
36
+ // Keep the literal specifier so bundlers (esbuild) can resolve it.
37
+ return require('@aws-sdk/client-scheduler');
38
+ } catch (error) {
39
+ const isSchedulerSdkMissing =
40
+ error &&
41
+ error.code === 'MODULE_NOT_FOUND' &&
42
+ typeof error.message === 'string' &&
43
+ error.message.includes(SCHEDULER_SDK);
44
+ if (isSchedulerSdkMissing) {
45
+ throw new Error(
46
+ `The EventBridge scheduler requires the "${SCHEDULER_SDK}" package, ` +
47
+ `which is not installed. Install it (\`npm install ${SCHEDULER_SDK}\`) ` +
48
+ 'to use the EventBridge scheduler provider, or use the mock scheduler provider ' +
49
+ '(SCHEDULER_PROVIDER=mock) for local development.',
50
+ { cause: error }
51
+ );
52
+ }
53
+ throw error;
54
+ }
55
+ }
56
+
24
57
  class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
25
58
  constructor({ region } = {}) {
26
59
  super();
60
+ const {
61
+ SchedulerClient,
62
+ CreateScheduleCommand,
63
+ DeleteScheduleCommand,
64
+ GetScheduleCommand,
65
+ ResourceNotFoundException,
66
+ } = loadSchedulerSdk();
67
+ this.sdk = {
68
+ CreateScheduleCommand,
69
+ DeleteScheduleCommand,
70
+ GetScheduleCommand,
71
+ ResourceNotFoundException,
72
+ };
27
73
  this.client = new SchedulerClient({
28
74
  region: region || process.env.AWS_REGION || 'us-east-1',
29
75
  });
@@ -42,7 +88,12 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
42
88
  * @param {Object} params.payload - Message payload
43
89
  * @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
44
90
  */
45
- async scheduleOneTime({ scheduleName, scheduleAt, queueResourceId, payload }) {
91
+ async scheduleOneTime({
92
+ scheduleName,
93
+ scheduleAt,
94
+ queueResourceId,
95
+ payload,
96
+ }) {
46
97
  if (!scheduleName) {
47
98
  throw new Error('scheduleName is required');
48
99
  }
@@ -59,8 +110,11 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
59
110
  }
60
111
 
61
112
  // Format date to AWS schedule expression (at(yyyy-mm-ddThh:mm:ss))
62
- const scheduleExpression = `at(${scheduleAt.toISOString().replace(/\.\d{3}Z$/, '')})`;
113
+ const scheduleExpression = `at(${scheduleAt
114
+ .toISOString()
115
+ .replace(/\.\d{3}Z$/, '')})`;
63
116
 
117
+ const { CreateScheduleCommand } = this.sdk;
64
118
  const command = new CreateScheduleCommand({
65
119
  Name: scheduleName,
66
120
  GroupName: this.scheduleGroupName,
@@ -107,6 +161,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
107
161
  throw new Error('scheduleName is required');
108
162
  }
109
163
 
164
+ const { DeleteScheduleCommand, ResourceNotFoundException } = this.sdk;
110
165
  const command = new DeleteScheduleCommand({
111
166
  Name: scheduleName,
112
167
  GroupName: this.scheduleGroupName,
@@ -141,6 +196,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
141
196
  throw new Error('scheduleName is required');
142
197
  }
143
198
 
199
+ const { GetScheduleCommand, ResourceNotFoundException } = this.sdk;
144
200
  const command = new GetScheduleCommand({
145
201
  Name: scheduleName,
146
202
  GroupName: this.scheduleGroupName,
@@ -153,9 +209,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
153
209
  // Format: at(yyyy-mm-ddThh:mm:ss)
154
210
  let scheduledAt = null;
155
211
  if (response.ScheduleExpression) {
156
- const match = response.ScheduleExpression.match(
157
- /^at\((.+)\)$/
158
- );
212
+ const match = response.ScheduleExpression.match(/^at\((.+)\)$/);
159
213
  if (match) {
160
214
  scheduledAt = new Date(match[1] + 'Z').toISOString();
161
215
  }
@@ -457,6 +457,35 @@ class IntegrationBase {
457
457
  );
458
458
  }
459
459
 
460
+ /**
461
+ * Insert-only mapping write; usable as an atomic claim/lock row.
462
+ * @throws {MappingAlreadyExistsError} If a mapping for sourceId exists
463
+ */
464
+ async createMapping(sourceId, mapping) {
465
+ if (!sourceId) {
466
+ throw new Error(`sourceId must be set`);
467
+ }
468
+ return await this.integrationMappingRepository.createMapping(
469
+ this.id,
470
+ sourceId,
471
+ mapping
472
+ );
473
+ }
474
+
475
+ /**
476
+ * Deletes the mapping for sourceId. A missing mapping is not an error
477
+ * (resolves with deletedCount 0).
478
+ */
479
+ async deleteMapping(sourceId) {
480
+ if (!sourceId) {
481
+ throw new Error(`sourceId must be set`);
482
+ }
483
+ return await this.integrationMappingRepository.deleteMapping(
484
+ this.id,
485
+ sourceId
486
+ );
487
+ }
488
+
460
489
  /**
461
490
  * CHILDREN CAN OVERRIDE THESE CONFIGURATION METHODS
462
491
  */
@@ -42,9 +42,6 @@ const {
42
42
  } = require('../modules/use-cases/get-entity-options-by-type');
43
43
  const { TestModuleAuth } = require('../modules/use-cases/test-module-auth');
44
44
  const { GetModule } = require('../modules/use-cases/get-module');
45
- const {
46
- CreateEntityFromCredential,
47
- } = require('../modules/use-cases/create-entity-from-credential');
48
45
  const {
49
46
  GetEntityOptionsById,
50
47
  } = require('../modules/use-cases/get-entity-options-by-id');
@@ -201,13 +198,6 @@ function createIntegrationRouter() {
201
198
  getModulesDefinitionFromIntegrationClasses(integrationClasses),
202
199
  });
203
200
 
204
- const createEntityFromCredential = new CreateEntityFromCredential({
205
- processAuthorizationCallback,
206
- credentialRepository,
207
- moduleDefinitions:
208
- getModulesDefinitionFromIntegrationClasses(integrationClasses),
209
- });
210
-
211
201
  const router = express();
212
202
 
213
203
  setIntegrationRoutes(router, authenticateUser, {
@@ -228,7 +218,6 @@ function createIntegrationRouter() {
228
218
  getEntityOptionsById,
229
219
  refreshEntityOptions,
230
220
  processAuthorizationCallback,
231
- createEntityFromCredential,
232
221
  });
233
222
  return router;
234
223
  }
@@ -513,7 +502,6 @@ function setEntityRoutes(router, authenticateUser, useCases) {
513
502
  getEntityOptionsById,
514
503
  refreshEntityOptions,
515
504
  processAuthorizationCallback,
516
- createEntityFromCredential,
517
505
  } = useCases;
518
506
 
519
507
  router.route('/api/authorize').get(
@@ -578,19 +566,35 @@ function setEntityRoutes(router, authenticateUser, useCases) {
578
566
  router.route('/api/entity').post(
579
567
  catchAsyncError(async (req, res) => {
580
568
  const user = await authenticateUser.execute(req);
569
+ const userId = user.getId();
581
570
  const params = checkRequiredParams(req.body, [
582
571
  'entityType',
583
572
  'data',
584
573
  ]);
585
574
  checkRequiredParams(req.body.data, ['credential_id']);
586
575
 
587
- res.json(
588
- await createEntityFromCredential.execute({
589
- user,
590
- entityType: params.entityType,
591
- credentialId: params.data.credential_id,
592
- })
576
+ // May want to pass along the user ID as well so credential ID's can't be fished???
577
+ const credential = await getCredentialForUser.execute(
578
+ params.data.credential_id,
579
+ userId
580
+ );
581
+
582
+ if (!credential) {
583
+ throw Boom.badRequest('Invalid credential ID');
584
+ }
585
+
586
+ const module = await getModuleInstanceFromType.execute(
587
+ userId,
588
+ params.entityType
593
589
  );
590
+ const entityDetails = await module.getEntityDetails(
591
+ module.api,
592
+ null,
593
+ null,
594
+ userId
595
+ );
596
+
597
+ res.json(await module.findOrCreateEntity(entityDetails));
594
598
  })
595
599
  );
596
600
 
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  toObjectId,
4
5
  fromObjectId,
@@ -180,6 +181,55 @@ class IntegrationMappingRepositoryDocumentDB extends IntegrationMappingRepositor
180
181
  return this._mapMapping(decryptedMapping);
181
182
  }
182
183
 
184
+ async createMapping(integrationId, sourceId, mapping) {
185
+ const now = new Date();
186
+ const encryptedDocument = await this.encryptionService.encryptFields(
187
+ 'IntegrationMapping',
188
+ {
189
+ integrationId,
190
+ sourceId:
191
+ sourceId === null || sourceId === undefined
192
+ ? null
193
+ : String(sourceId),
194
+ mapping,
195
+ createdAt: now,
196
+ updatedAt: now,
197
+ }
198
+ );
199
+
200
+ let insertedId;
201
+ try {
202
+ insertedId = await insertOne(
203
+ this.prisma,
204
+ 'IntegrationMapping',
205
+ encryptedDocument
206
+ );
207
+ } catch (error) {
208
+ if (error.code === 11000) {
209
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
210
+ cause: error,
211
+ });
212
+ }
213
+ throw error;
214
+ }
215
+
216
+ const created = await findOne(this.prisma, 'IntegrationMapping', {
217
+ _id: insertedId,
218
+ });
219
+ if (!created) {
220
+ throw new Error(
221
+ 'Failed to create mapping: Document not found after insert. ' +
222
+ 'This indicates a database consistency issue.'
223
+ );
224
+ }
225
+ return this._mapMapping(
226
+ await this.encryptionService.decryptFields(
227
+ 'IntegrationMapping',
228
+ created
229
+ )
230
+ );
231
+ }
232
+
183
233
  async findMappingsByIntegration(integrationId) {
184
234
  const filter = {};
185
235
  if (integrationId) filter.integrationId = integrationId;
@@ -39,6 +39,21 @@ class IntegrationMappingRepositoryInterface {
39
39
  throw new Error('Method upsertMapping must be implemented by subclass');
40
40
  }
41
41
 
42
+ /**
43
+ * Insert a mapping, failing if one already exists for the
44
+ * (integrationId, sourceId) pair. Atomic: usable as a claim/lock row.
45
+ *
46
+ * @param {string|number} integrationId - The integration ID
47
+ * @param {string} sourceId - The source ID for lookup
48
+ * @param {Object} mapping - The mapping data
49
+ * @returns {Promise<Object>} The created mapping document
50
+ * @throws {MappingAlreadyExistsError} If the pair already exists
51
+ * @abstract
52
+ */
53
+ async createMapping(integrationId, sourceId, mapping) {
54
+ throw new Error('createMapping must be implemented by subclass');
55
+ }
56
+
42
57
  /**
43
58
  * Find all mappings for an integration
44
59
  *
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  assertMappingWrittenUnencrypted,
4
5
  decryptQueriedMappings,
@@ -93,6 +94,34 @@ class IntegrationMappingRepositoryMongo extends IntegrationMappingRepositoryInte
93
94
  });
94
95
  }
95
96
 
97
+ /**
98
+ * Insert a mapping; fails if (integrationId, sourceId) already exists
99
+ *
100
+ * @param {string} integrationId - The integration ID
101
+ * @param {string} sourceId - The source ID
102
+ * @param {Object} mapping - The mapping data
103
+ * @returns {Promise<Object>} The created mapping document
104
+ * @throws {MappingAlreadyExistsError} If the pair already exists
105
+ */
106
+ async createMapping(integrationId, sourceId, mapping) {
107
+ try {
108
+ return await this.prisma.integrationMapping.create({
109
+ data: {
110
+ integrationId,
111
+ sourceId: this._toString(sourceId),
112
+ mapping,
113
+ },
114
+ });
115
+ } catch (error) {
116
+ if (error.code === 'P2002') {
117
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
118
+ cause: error,
119
+ });
120
+ }
121
+ throw error;
122
+ }
123
+ }
124
+
96
125
  /**
97
126
  * Find all mappings for an integration
98
127
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  assertMappingWrittenUnencrypted,
4
5
  decryptQueriedMappings,
@@ -150,6 +151,35 @@ class IntegrationMappingRepositoryPostgres extends IntegrationMappingRepositoryI
150
151
  return this._convertMappingIds(result);
151
152
  }
152
153
 
154
+ /**
155
+ * Insert a mapping; fails if (integrationId, sourceId) already exists
156
+ *
157
+ * @param {string} integrationId - The integration ID
158
+ * @param {string} sourceId - The source ID
159
+ * @param {Object} mapping - The mapping data
160
+ * @returns {Promise<Object>} The created mapping document
161
+ * @throws {MappingAlreadyExistsError} If the pair already exists
162
+ */
163
+ async createMapping(integrationId, sourceId, mapping) {
164
+ try {
165
+ const created = await this.prisma.integrationMapping.create({
166
+ data: {
167
+ integrationId: this._stringToInt(integrationId),
168
+ sourceId: this._toString(sourceId),
169
+ mapping,
170
+ },
171
+ });
172
+ return this._convertMappingIds(created);
173
+ } catch (error) {
174
+ if (error.code === 'P2002') {
175
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
176
+ cause: error,
177
+ });
178
+ }
179
+ throw error;
180
+ }
181
+ }
182
+
153
183
  /**
154
184
  * Find all mappings for an integration
155
185
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  IntegrationMappingRepositoryInterface,
4
5
  } = require('./integration-mapping-repository-interface');
@@ -69,6 +70,34 @@ class IntegrationMappingRepository extends IntegrationMappingRepositoryInterface
69
70
  });
70
71
  }
71
72
 
73
+ /**
74
+ * Insert a mapping; fails if (integrationId, sourceId) already exists
75
+ *
76
+ * @param {string} integrationId - The integration ID
77
+ * @param {string} sourceId - The source ID
78
+ * @param {Object} mapping - The mapping data
79
+ * @returns {Promise<Object>} The created mapping document
80
+ * @throws {MappingAlreadyExistsError} If the pair already exists
81
+ */
82
+ async createMapping(integrationId, sourceId, mapping) {
83
+ try {
84
+ return await this.prisma.integrationMapping.create({
85
+ data: {
86
+ integrationId,
87
+ sourceId,
88
+ mapping,
89
+ },
90
+ });
91
+ } catch (error) {
92
+ if (error.code === 'P2002') {
93
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
94
+ cause: error,
95
+ });
96
+ }
97
+ throw error;
98
+ }
99
+ }
100
+
72
101
  /**
73
102
  * Find all mappings for an integration
74
103
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -164,6 +164,38 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
164
164
  return this._mapIntegration(created);
165
165
  }
166
166
 
167
+ async addEntitiesToIntegration(integrationId, entityIds) {
168
+ const objectId = toObjectId(integrationId);
169
+ if (!objectId) return null;
170
+ const result = await updateOne(
171
+ this.prisma,
172
+ 'Integration',
173
+ { _id: objectId },
174
+ {
175
+ $addToSet: { entityIds: { $each: toObjectIdArray(entityIds) } },
176
+ $set: { updatedAt: { $date: new Date().toISOString() } },
177
+ }
178
+ );
179
+ if (!result?.n) return null;
180
+ return this.findIntegrationById(integrationId);
181
+ }
182
+
183
+ async removeEntitiesFromIntegration(integrationId, entityIds) {
184
+ const objectId = toObjectId(integrationId);
185
+ if (!objectId) return null;
186
+ const result = await updateOne(
187
+ this.prisma,
188
+ 'Integration',
189
+ { _id: objectId },
190
+ {
191
+ $pullAll: { entityIds: toObjectIdArray(entityIds) },
192
+ $set: { updatedAt: { $date: new Date().toISOString() } },
193
+ }
194
+ );
195
+ if (!result?.n) return null;
196
+ return this.findIntegrationById(integrationId);
197
+ }
198
+
167
199
  async findIntegrationByUserId(userId) {
168
200
  const objectId = toObjectId(userId);
169
201
  if (!objectId) return null;