@friggframework/core 2.0.0--canary.730.f2ba24a.0 → 2.0.0--canary.656.6eb85ab.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CLAUDE.md +14 -42
  2. package/application/commands/README.md +11 -17
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +0 -63
  5. package/core/CLAUDE.md +3 -1
  6. package/core/create-handler.js +3 -0
  7. package/core/index.js +6 -0
  8. package/core/invocation-deadline.js +91 -0
  9. package/core/invocation-scope.js +30 -24
  10. package/database/documentdb-encryption-service.js +33 -2
  11. package/database/documentdb-utils.js +1 -4
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/encryption-schema-registry.js +29 -109
  14. package/database/encryption/field-encryption-service.js +16 -55
  15. package/database/encryption/prisma-encryption-extension.js +9 -6
  16. package/database/prisma.js +1 -10
  17. package/encrypt/Cryptor.js +38 -90
  18. package/errors/fetch-error.js +11 -18
  19. package/errors/index.js +2 -4
  20. package/errors/rate-limit-error.js +45 -0
  21. package/handlers/WEBHOOKS.md +0 -29
  22. package/handlers/app-definition-loader.js +2 -9
  23. package/handlers/app-handler-helpers.js +1 -12
  24. package/handlers/backend-utils.js +2 -1
  25. package/handlers/workers/integration-defined-workers.js +2 -0
  26. package/index.js +18 -2
  27. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
  28. package/integrations/integration-base.js +9 -52
  29. package/integrations/integration-router.js +22 -30
  30. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  31. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  32. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  33. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  34. package/integrations/repositories/integration-mapping-repository.js +0 -29
  35. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  36. package/integrations/repositories/integration-repository-interface.js +0 -30
  37. package/integrations/repositories/integration-repository-mongo.js +1 -53
  38. package/integrations/repositories/integration-repository-postgres.js +0 -58
  39. package/integrations/repositories/process-repository-mongo.js +1 -1
  40. package/integrations/use-cases/create-integration.js +19 -57
  41. package/integrations/use-cases/delete-integration-for-user.js +11 -8
  42. package/integrations/use-cases/get-integration-instance.js +12 -12
  43. package/integrations/use-cases/update-integration.js +12 -12
  44. package/jest-setup.js +2 -13
  45. package/jest-teardown.js +2 -5
  46. package/jest.config.js +0 -4
  47. package/logs/serialize.js +15 -0
  48. package/modules/requester/rate-limit/index.js +4 -0
  49. package/modules/requester/rate-limit/parsers.js +245 -0
  50. package/modules/requester/rate-limit/policy.js +304 -0
  51. package/modules/requester/requester.js +187 -9
  52. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  53. package/modules/use-cases/get-module.js +8 -29
  54. package/modules/use-cases/process-authorization-callback.js +27 -78
  55. package/modules/use-cases/refresh-entity-options.js +5 -7
  56. package/modules/use-cases/test-module-auth.js +5 -7
  57. package/modules/utils/map-module-dto.js +3 -5
  58. package/package.json +7 -10
  59. package/queues/queuer-util.js +5 -6
  60. package/token/repositories/token-repository-documentdb.js +1 -13
  61. package/token/repositories/token-repository-mongo.js +1 -13
  62. package/token/repositories/token-repository-postgres.js +1 -13
  63. package/types/core/index.d.ts +33 -0
  64. package/types/errors/index.d.ts +47 -0
  65. package/types/module-plugin/index.d.ts +43 -0
  66. package/user/tests/doubles/test-user-repository.js +1 -1
  67. package/user/use-cases/authenticate-user.js +7 -23
  68. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  69. package/database/encryption/ciphertext-format.js +0 -24
  70. package/errors/mapping-already-exists-error.js +0 -14
  71. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  72. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  73. package/integrations/utils/assert-entity-ids-input.js +0 -42
  74. package/jest.db.config.js +0 -23
  75. package/modules/use-cases/create-entity-from-credential.js +0 -105
  76. package/modules/utils/find-module-definition.js +0 -23
  77. package/modules/utils/to-credential-id.js +0 -14
@@ -1,9 +1,6 @@
1
1
  const { findNearestBackendPackageJson } = require('@friggframework/core/utils');
2
2
  const path = require('node:path');
3
3
  const fs = require('fs-extra');
4
- const {
5
- applyAppDefinitionDefaults,
6
- } = require('@friggframework/schemas/app-definition');
7
4
  const { resolveTelemetryConfig } = require('../telemetry/telemetry-config');
8
5
  const { registerDeniedKeys } = require('../logs/denied-keys');
9
6
  const {
@@ -36,9 +33,7 @@ function registerCredentialLogKeys(appDefinition, integrations) {
36
33
  * @function loadAppDefinition
37
34
  * @description Searches for the nearest backend package.json, loads the corresponding index.js file,
38
35
  * and extracts the application definition containing integrations and user configuration.
39
- * The defaults declared in the app-definition schema are applied first (ADR-051), so
40
- * `userConfig` always holds a complete user config, also when the app omits `user`.
41
- * @returns {{integrations: Array<object>, userConfig: object, adminScripts: Array<object>, reports: Array<object>, admin: object, telemetry: object, logging: object | null}} An object containing the application definition.
36
+ * @returns {{integrations: Array<object>, userConfig: object | null, adminScripts: Array<object>, reports: Array<object>, admin: object, telemetry: object, logging: object | null}} An object containing the application definition.
42
37
  * @throws {Error} Throws error if backend package.json cannot be found.
43
38
  * @throws {Error} Throws error if index.js file cannot be found in the backend directory.
44
39
  * @example
@@ -58,9 +53,7 @@ function loadAppDefinition() {
58
53
  }
59
54
 
60
55
  const backendJsFile = require(backendFilePath);
61
- // The one place schema defaults are applied at runtime (ADR-051): a
62
- // default in app-definition.schema.json is the value core sees.
63
- const appDefinition = applyAppDefinitionDefaults(backendJsFile.Definition);
56
+ const appDefinition = backendJsFile.Definition;
64
57
 
65
58
  const {
66
59
  integrations = [],
@@ -9,17 +9,6 @@ const serverlessHttp = require('serverless-http');
9
9
 
10
10
  const log = getLogger('frigg.http');
11
11
 
12
- const isHttpErrorStatus = (statusCode) =>
13
- Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599;
14
-
15
- const toBoom = (err) => {
16
- if (err.isBoom) return err;
17
- if (err.isClientSafe === true && isHttpErrorStatus(err.statusCode)) {
18
- return Boom.boomify(err, { statusCode: err.statusCode });
19
- }
20
- return Boom.boomify(err);
21
- };
22
-
23
12
  const createApp = (applyMiddleware) => {
24
13
  const app = express();
25
14
 
@@ -38,7 +27,7 @@ const createApp = (applyMiddleware) => {
38
27
 
39
28
  // The express boundary: send the error response and log it one time.
40
29
  app.use((err, req, res, next) => {
41
- const boomError = toBoom(err);
30
+ const boomError = err.isBoom ? err : Boom.boomify(err);
42
31
  const {
43
32
  output: { statusCode = 500 },
44
33
  } = boomError;
@@ -285,7 +285,8 @@ const createQueueWorker = (integrationClass) => {
285
285
  status >= 400 &&
286
286
  status < 500 &&
287
287
  status !== 408 &&
288
- status !== 429
288
+ status !== 429 &&
289
+ !error.isRateLimited
289
290
  ) {
290
291
  error.isHaltError = true;
291
292
  console.warn(
@@ -1,6 +1,7 @@
1
1
  const { createHandler } = require('@friggframework/core');
2
2
  const { loadAppDefinition } = require('../app-definition-loader');
3
3
  const { createQueueWorker } = require('../backend-utils');
4
+ const { MAX_IN_PROCESS_WAIT_MS } = require('../../core/invocation-deadline');
4
5
  // TODO(Phase 2): mount extension-declared workers in addition to the per-integration
5
6
  // default queue worker. Today, getExtensionWorkers(IntegrationClass) returns the
6
7
  // declared workers but they are not yet bound to dedicated SQS sources. Extension-
@@ -19,6 +20,7 @@ integrationClasses.forEach((IntegrationClass) => {
19
20
  queueWorker: createHandler({
20
21
  eventName: `Queue Worker for ${IntegrationClass.Definition.name}`,
21
22
  isUserFacingResponse: false,
23
+ maxInProcessWaitMs: MAX_IN_PROCESS_WAIT_MS.queueWorker,
22
24
  method: async (event, context) => {
23
25
  const worker = new defaultQueueWorker();
24
26
  return await worker.run(event, context);
package/index.js CHANGED
@@ -12,6 +12,8 @@ const {
12
12
  loadInstalledModules,
13
13
  createHandler,
14
14
  runInvocationScope,
15
+ runWithInvocationDeadline,
16
+ remainingInvocationMs,
15
17
  } = require('./core/index');
16
18
  const {
17
19
  prisma,
@@ -55,9 +57,9 @@ const {
55
57
  BaseError,
56
58
  FetchError,
57
59
  HaltError,
60
+ RateLimitError,
58
61
  RequiredPropertyError,
59
62
  ParameterTypeError,
60
- MappingAlreadyExistsError,
61
63
  } = require('./errors/index');
62
64
  const {
63
65
  IntegrationBase,
@@ -101,6 +103,12 @@ const {
101
103
  ModuleConstants,
102
104
  ModuleFactory,
103
105
  } = require('./modules/index');
106
+ const {
107
+ classifyRateLimit,
108
+ parseRetryAfter,
109
+ parseResetHeaders,
110
+ parseIetfRateLimit,
111
+ } = require('./modules/requester/rate-limit');
104
112
  const application = require('./application');
105
113
  const utils = require('./utils');
106
114
 
@@ -121,6 +129,8 @@ module.exports = {
121
129
  loadInstalledModules,
122
130
  createHandler,
123
131
  runInvocationScope,
132
+ runWithInvocationDeadline,
133
+ remainingInvocationMs,
124
134
 
125
135
  // database
126
136
  prisma,
@@ -143,9 +153,15 @@ module.exports = {
143
153
  BaseError,
144
154
  FetchError,
145
155
  HaltError,
156
+ RateLimitError,
146
157
  RequiredPropertyError,
147
158
  ParameterTypeError,
148
- MappingAlreadyExistsError,
159
+
160
+ // rate limit
161
+ classifyRateLimit,
162
+ parseRetryAfter,
163
+ parseResetHeaders,
164
+ parseIetfRateLimit,
149
165
 
150
166
  // integrations
151
167
  IntegrationBase,
@@ -11,65 +11,19 @@
11
11
  * This adapter implements SchedulerServiceInterface for AWS EventBridge Scheduler.
12
12
  */
13
13
 
14
- const { SchedulerServiceInterface } = require('./scheduler-service-interface');
15
-
16
- const SCHEDULER_SDK = '@aws-sdk/client-scheduler';
14
+ const {
15
+ SchedulerClient,
16
+ CreateScheduleCommand,
17
+ DeleteScheduleCommand,
18
+ GetScheduleCommand,
19
+ ResourceNotFoundException,
20
+ } = require('@aws-sdk/client-scheduler');
17
21
 
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
- }
22
+ const { SchedulerServiceInterface } = require('./scheduler-service-interface');
56
23
 
57
24
  class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
58
25
  constructor({ region } = {}) {
59
26
  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
- };
73
27
  this.client = new SchedulerClient({
74
28
  region: region || process.env.AWS_REGION || 'us-east-1',
75
29
  });
@@ -88,12 +42,7 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
88
42
  * @param {Object} params.payload - Message payload
89
43
  * @returns {Promise<{scheduledJobId: string, scheduledAt: string}>}
90
44
  */
91
- async scheduleOneTime({
92
- scheduleName,
93
- scheduleAt,
94
- queueResourceId,
95
- payload,
96
- }) {
45
+ async scheduleOneTime({ scheduleName, scheduleAt, queueResourceId, payload }) {
97
46
  if (!scheduleName) {
98
47
  throw new Error('scheduleName is required');
99
48
  }
@@ -110,11 +59,8 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
110
59
  }
111
60
 
112
61
  // Format date to AWS schedule expression (at(yyyy-mm-ddThh:mm:ss))
113
- const scheduleExpression = `at(${scheduleAt
114
- .toISOString()
115
- .replace(/\.\d{3}Z$/, '')})`;
62
+ const scheduleExpression = `at(${scheduleAt.toISOString().replace(/\.\d{3}Z$/, '')})`;
116
63
 
117
- const { CreateScheduleCommand } = this.sdk;
118
64
  const command = new CreateScheduleCommand({
119
65
  Name: scheduleName,
120
66
  GroupName: this.scheduleGroupName,
@@ -161,7 +107,6 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
161
107
  throw new Error('scheduleName is required');
162
108
  }
163
109
 
164
- const { DeleteScheduleCommand, ResourceNotFoundException } = this.sdk;
165
110
  const command = new DeleteScheduleCommand({
166
111
  Name: scheduleName,
167
112
  GroupName: this.scheduleGroupName,
@@ -196,7 +141,6 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
196
141
  throw new Error('scheduleName is required');
197
142
  }
198
143
 
199
- const { GetScheduleCommand, ResourceNotFoundException } = this.sdk;
200
144
  const command = new GetScheduleCommand({
201
145
  Name: scheduleName,
202
146
  GroupName: this.scheduleGroupName,
@@ -209,7 +153,9 @@ class EventBridgeSchedulerAdapter extends SchedulerServiceInterface {
209
153
  // Format: at(yyyy-mm-ddThh:mm:ss)
210
154
  let scheduledAt = null;
211
155
  if (response.ScheduleExpression) {
212
- const match = response.ScheduleExpression.match(/^at\((.+)\)$/);
156
+ const match = response.ScheduleExpression.match(
157
+ /^at\((.+)\)$/
158
+ );
213
159
  if (match) {
214
160
  scheduledAt = new Date(match[1] + 'Z').toISOString();
215
161
  }
@@ -457,35 +457,6 @@ 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
-
489
460
  /**
490
461
  * CHILDREN CAN OVERRIDE THESE CONFIGURATION METHODS
491
462
  */
@@ -557,28 +528,15 @@ class IntegrationBase {
557
528
  }
558
529
  }
559
530
  }
560
- const dynamicUserActions = await this._loadDynamicUserActionEvents();
561
- const filteredDynamicActions = Object.fromEntries(
562
- Object.entries(dynamicUserActions).filter(
563
- ([_, event]) =>
564
- event.type === constantsToBeMigrated.types.USER_ACTION &&
565
- (!actionType || event.userActionType === actionType)
566
- )
567
- );
568
- return { ...userActions, ...filteredDynamicActions };
569
- }
570
-
571
- async _loadDynamicUserActionEvents() {
572
531
  const dynamicUserActions = await this.loadDynamicUserActions();
573
- return Object.fromEntries(
574
- Object.entries(dynamicUserActions).map(([key, event]) => [
575
- key,
576
- {
577
- ...event,
578
- type: event.type ?? constantsToBeMigrated.types.USER_ACTION,
579
- },
580
- ])
581
- );
532
+ const filteredDynamicActions = actionType
533
+ ? Object.fromEntries(
534
+ Object.entries(dynamicUserActions).filter(
535
+ ([_, event]) => event.userActionType === actionType
536
+ )
537
+ )
538
+ : dynamicUserActions;
539
+ return { ...userActions, ...filteredDynamicActions };
582
540
  }
583
541
 
584
542
  async getActionOptions(actionId, data) {
@@ -860,8 +818,7 @@ class IntegrationBase {
860
818
 
861
819
  async initialize() {
862
820
  try {
863
- const additionalUserActions =
864
- await this._loadDynamicUserActionEvents();
821
+ const additionalUserActions = await this.loadDynamicUserActions();
865
822
  this.events = { ...this.events, ...additionalUserActions };
866
823
  } catch (e) {
867
824
  this.addError(e);
@@ -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
  }
@@ -257,15 +246,6 @@ function checkRequiredParams(params, requiredKeys) {
257
246
  return returnDict;
258
247
  }
259
248
 
260
- function assertUserAction(integration, actionId) {
261
- if (
262
- !Object.hasOwn(integration.events, actionId) ||
263
- integration.events[actionId].type !== 'USER_ACTION'
264
- ) {
265
- throw Boom.notFound(`User action ${actionId} does not exist`);
266
- }
267
- }
268
-
269
249
  /**
270
250
  * Sets up integration-related routes on the provided Express router
271
251
  * @param {express.Router} router - Express router instance to add routes to
@@ -402,7 +382,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
402
382
  params.integrationId,
403
383
  user.getId()
404
384
  );
405
- assertUserAction(integration, params.actionId);
406
385
 
407
386
  res.json(
408
387
  await integration.send('GET_USER_ACTION_OPTIONS', {
@@ -428,7 +407,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
428
407
  params.integrationId,
429
408
  user.getId()
430
409
  );
431
- assertUserAction(integration, params.actionId);
432
410
 
433
411
  res.json(
434
412
  await integration.send('REFRESH_USER_ACTION_OPTIONS', {
@@ -450,7 +428,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
450
428
  params.integrationId,
451
429
  user.getId()
452
430
  );
453
- assertUserAction(integration, params.actionId);
454
431
  res.json(await integration.send(params.actionId, req.body));
455
432
  })
456
433
  );
@@ -525,7 +502,6 @@ function setEntityRoutes(router, authenticateUser, useCases) {
525
502
  getEntityOptionsById,
526
503
  refreshEntityOptions,
527
504
  processAuthorizationCallback,
528
- createEntityFromCredential,
529
505
  } = useCases;
530
506
 
531
507
  router.route('/api/authorize').get(
@@ -590,19 +566,35 @@ function setEntityRoutes(router, authenticateUser, useCases) {
590
566
  router.route('/api/entity').post(
591
567
  catchAsyncError(async (req, res) => {
592
568
  const user = await authenticateUser.execute(req);
569
+ const userId = user.getId();
593
570
  const params = checkRequiredParams(req.body, [
594
571
  'entityType',
595
572
  'data',
596
573
  ]);
597
574
  checkRequiredParams(req.body.data, ['credential_id']);
598
575
 
599
- res.json(
600
- await createEntityFromCredential.execute({
601
- user,
602
- entityType: params.entityType,
603
- credentialId: params.data.credential_id,
604
- })
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
605
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
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));
606
598
  })
607
599
  );
608
600
 
@@ -1,5 +1,4 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { MappingAlreadyExistsError } = require('../../errors');
3
2
  const {
4
3
  toObjectId,
5
4
  fromObjectId,
@@ -181,55 +180,6 @@ class IntegrationMappingRepositoryDocumentDB extends IntegrationMappingRepositor
181
180
  return this._mapMapping(decryptedMapping);
182
181
  }
183
182
 
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
-
233
183
  async findMappingsByIntegration(integrationId) {
234
184
  const filter = {};
235
185
  if (integrationId) filter.integrationId = integrationId;
@@ -39,21 +39,6 @@ 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
-
57
42
  /**
58
43
  * Find all mappings for an integration
59
44
  *
@@ -1,5 +1,4 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { MappingAlreadyExistsError } = require('../../errors');
3
2
  const {
4
3
  assertMappingWrittenUnencrypted,
5
4
  decryptQueriedMappings,
@@ -94,34 +93,6 @@ class IntegrationMappingRepositoryMongo extends IntegrationMappingRepositoryInte
94
93
  });
95
94
  }
96
95
 
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
-
125
96
  /**
126
97
  * Find all mappings for an integration
127
98
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -1,5 +1,4 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { MappingAlreadyExistsError } = require('../../errors');
3
2
  const {
4
3
  assertMappingWrittenUnencrypted,
5
4
  decryptQueriedMappings,
@@ -151,35 +150,6 @@ class IntegrationMappingRepositoryPostgres extends IntegrationMappingRepositoryI
151
150
  return this._convertMappingIds(result);
152
151
  }
153
152
 
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
-
183
153
  /**
184
154
  * Find all mappings for an integration
185
155
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -1,5 +1,4 @@
1
1
  const { prisma } = require('../../database/prisma');
2
- const { MappingAlreadyExistsError } = require('../../errors');
3
2
  const {
4
3
  IntegrationMappingRepositoryInterface,
5
4
  } = require('./integration-mapping-repository-interface');
@@ -70,34 +69,6 @@ class IntegrationMappingRepository extends IntegrationMappingRepositoryInterface
70
69
  });
71
70
  }
72
71
 
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
-
101
72
  /**
102
73
  * Find all mappings for an integration
103
74
  * Replaces: IntegrationMapping.find({ integration: integrationId })