@friggframework/core 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.657.18fb0ee.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 (101) hide show
  1. package/CLAUDE.md +93 -48
  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 +30 -1
  6. package/core/Worker.js +310 -9
  7. package/core/create-handler.js +3 -0
  8. package/core/index.js +6 -0
  9. package/core/invocation-deadline.js +91 -0
  10. package/core/invocation-scope.js +30 -24
  11. package/database/documentdb-encryption-service.js +33 -2
  12. package/database/documentdb-utils.js +1 -4
  13. package/database/encryption/README.md +3 -3
  14. package/database/encryption/encryption-schema-registry.js +29 -109
  15. package/database/encryption/field-encryption-service.js +16 -55
  16. package/database/encryption/prisma-encryption-extension.js +9 -6
  17. package/database/prisma.js +1 -10
  18. package/encrypt/Cryptor.js +38 -90
  19. package/errors/fetch-error.js +11 -18
  20. package/errors/index.js +2 -4
  21. package/errors/rate-limit-error.js +45 -0
  22. package/generated/prisma-mongodb/edge.js +2 -6
  23. package/generated/prisma-mongodb/index.js +2 -10
  24. package/generated/prisma-mongodb/package.json +1 -1
  25. package/generated/prisma-mongodb/schema.prisma +1 -1
  26. package/generated/prisma-mongodb/wasm.js +2 -6
  27. package/generated/prisma-postgresql/edge.js +2 -6
  28. package/generated/prisma-postgresql/index.js +2 -10
  29. package/generated/prisma-postgresql/package.json +1 -1
  30. package/generated/prisma-postgresql/schema.prisma +1 -1
  31. package/generated/prisma-postgresql/wasm.js +2 -6
  32. package/handlers/WEBHOOKS.md +0 -29
  33. package/handlers/app-definition-loader.js +2 -9
  34. package/handlers/app-handler-helpers.js +1 -12
  35. package/handlers/backend-utils.js +30 -1
  36. package/handlers/workers/integration-defined-workers.js +2 -0
  37. package/index.js +18 -2
  38. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +15 -67
  39. package/integrations/integration-base.js +9 -52
  40. package/integrations/integration-router.js +22 -30
  41. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  42. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  43. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  44. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  45. package/integrations/repositories/integration-mapping-repository.js +0 -29
  46. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  47. package/integrations/repositories/integration-repository-interface.js +0 -30
  48. package/integrations/repositories/integration-repository-mongo.js +1 -53
  49. package/integrations/repositories/integration-repository-postgres.js +0 -58
  50. package/integrations/repositories/process-repository-mongo.js +1 -1
  51. package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
  52. package/integrations/use-cases/create-integration.js +19 -57
  53. package/integrations/use-cases/delete-integration-for-user.js +11 -8
  54. package/integrations/use-cases/get-integration-instance.js +12 -12
  55. package/integrations/use-cases/index.js +5 -1
  56. package/integrations/use-cases/record-rate-limit-wait.js +36 -0
  57. package/integrations/use-cases/update-integration.js +12 -12
  58. package/jest-setup.js +2 -13
  59. package/jest-teardown.js +2 -5
  60. package/jest.config.js +0 -4
  61. package/logs/serialize.js +15 -0
  62. package/modules/requester/oauth-2.js +7 -0
  63. package/modules/requester/rate-limit/index.js +4 -0
  64. package/modules/requester/rate-limit/parsers.js +245 -0
  65. package/modules/requester/rate-limit/policy.js +304 -0
  66. package/modules/requester/requester.js +187 -9
  67. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  68. package/modules/use-cases/get-module.js +8 -29
  69. package/modules/use-cases/process-authorization-callback.js +27 -78
  70. package/modules/use-cases/refresh-entity-options.js +5 -7
  71. package/modules/use-cases/test-module-auth.js +5 -7
  72. package/modules/utils/map-module-dto.js +3 -5
  73. package/package.json +8 -9
  74. package/prisma-mongodb/schema.prisma +1 -1
  75. package/prisma-postgresql/schema.prisma +1 -1
  76. package/queues/queue-deferral.js +74 -0
  77. package/queues/queue-delivery.js +1 -0
  78. package/queues/queuer-util.js +6 -7
  79. package/telemetry/otel-telemetry.js +3 -76
  80. package/telemetry/telemetry-config.js +5 -16
  81. package/telemetry/telemetry-runtime.js +1 -14
  82. package/token/repositories/token-repository-documentdb.js +1 -13
  83. package/token/repositories/token-repository-mongo.js +1 -13
  84. package/token/repositories/token-repository-postgres.js +1 -13
  85. package/types/core/index.d.ts +52 -0
  86. package/types/errors/index.d.ts +47 -0
  87. package/types/module-plugin/index.d.ts +43 -0
  88. package/user/tests/doubles/test-user-repository.js +1 -1
  89. package/user/use-cases/authenticate-user.js +7 -23
  90. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  91. package/database/encryption/ciphertext-format.js +0 -24
  92. package/errors/mapping-already-exists-error.js +0 -14
  93. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  94. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  95. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  96. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  97. package/integrations/utils/assert-entity-ids-input.js +0 -42
  98. package/jest.db.config.js +0 -23
  99. package/modules/use-cases/create-entity-from-credential.js +0 -105
  100. package/modules/utils/find-module-definition.js +0 -23
  101. package/modules/utils/to-credential-id.js +0 -14
@@ -257,19 +257,7 @@ class TokenRepositoryPostgres extends TokenRepositoryInterface {
257
257
  */
258
258
  getJSONTokenFromBase64BufferToken(buffer) {
259
259
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
260
- let jsonToken;
261
- try {
262
- jsonToken = JSON.parse(tokenStr);
263
- } catch {
264
- jsonToken = null;
265
- }
266
- if (
267
- !['string', 'number'].includes(typeof jsonToken?.id) ||
268
- typeof jsonToken?.token !== 'string'
269
- ) {
270
- throw new ClientSafeError('Invalid Token: Token is malformed', 401);
271
- }
272
- return jsonToken;
260
+ return JSON.parse(tokenStr);
273
261
  }
274
262
  }
275
263
 
@@ -1,5 +1,10 @@
1
1
  declare module "@friggframework/core" {
2
2
  import type { SendMessageCommandInput } from "@aws-sdk/client-sqs";
3
+ import type { RateLimitHint } from "@friggframework/errors";
4
+ import type {
5
+ RateLimitPolicy,
6
+ RateLimitSignal,
7
+ } from "@friggframework/module-plugin";
3
8
 
4
9
  export class Delegate implements IFriggDelegate {
5
10
  delegate: any;
@@ -42,8 +47,27 @@ declare module "@friggframework/core" {
42
47
  send(params: object & { QueueUrl: any }, delay?: number): Promise<string>;
43
48
 
44
49
  sendAsyncSQSMessage(params: SendSQSMessageParams): Promise<string>;
50
+
51
+ recordRateLimitWait(
52
+ body: object,
53
+ error: Error,
54
+ state: RateLimitWaitState
55
+ ): Promise<void>;
56
+
57
+ clearRateLimitWait(
58
+ body: object,
59
+ options?: { deferralId?: string }
60
+ ): Promise<void>;
45
61
  }
46
62
 
63
+ export type RateLimitWaitState = {
64
+ status: "WAITING" | "EXHAUSTED";
65
+ mechanism: "delay" | "schedule" | "visibility" | "none";
66
+ deferrals: number;
67
+ deferralId?: string;
68
+ retryAt: Date;
69
+ };
70
+
47
71
  interface IWorker {
48
72
  getQueueURL(params: GetQueueURLParams): Promise<string | undefined>;
49
73
  run(params: { Records: any }, context?: object): Promise<BatchItemFailuresResponse>;
@@ -53,6 +77,34 @@ declare module "@friggframework/core" {
53
77
 
54
78
  export function loadInstalledModules(): any[];
55
79
 
80
+ export function runWithInvocationDeadline<T>(
81
+ limits: { deadlineAt?: number; maxInProcessWaitMs?: number },
82
+ fn: () => T
83
+ ): T;
84
+
85
+ export function remainingInvocationMs(now?: number): number;
86
+
87
+ export function classifyRateLimit(
88
+ policy: RateLimitPolicy | undefined,
89
+ signal: RateLimitSignal,
90
+ options?: { now?: number; onClassifyError?: (error: Error) => void }
91
+ ): RateLimitHint | null;
92
+
93
+ export function parseRetryAfter(
94
+ value: string | null | undefined,
95
+ options?: { now?: number }
96
+ ): RateLimitHint | null;
97
+
98
+ export function parseResetHeaders(
99
+ headers: object | undefined,
100
+ options?: { now?: number }
101
+ ): RateLimitHint | null;
102
+
103
+ export function parseIetfRateLimit(
104
+ headers: object | undefined,
105
+ options?: { now?: number }
106
+ ): RateLimitHint | null;
107
+
56
108
  type GetQueueURLParams = {
57
109
  QueueName: string;
58
110
  QueueOwnerAWSAccountId?: string;
@@ -16,10 +16,57 @@ declare module "@friggframework/errors" {
16
16
  readonly body: any;
17
17
  isTimeout?: boolean;
18
18
  timeoutMs?: number;
19
+ isRateLimited?: boolean;
20
+ reason?: RateLimitReason;
19
21
 
20
22
  static create(options?: CreateFetchErrorParams): Promise<FetchError>;
21
23
  }
22
24
 
25
+ export type RateLimitReason =
26
+ | "burst"
27
+ | "daily"
28
+ | "monthly"
29
+ | "concurrency"
30
+ | "unknown";
31
+
32
+ export type RateLimitSource = "header" | "body" | "static" | "backoff";
33
+
34
+ export type RateLimitHint = {
35
+ retryAt: Date;
36
+ waitMs: number;
37
+ reason: RateLimitReason;
38
+ policy?: string;
39
+ remaining?: number;
40
+ source: RateLimitSource;
41
+ };
42
+
43
+ export class RateLimitError extends FetchError {
44
+ constructor(options?: RateLimitErrorConstructor);
45
+
46
+ isRateLimited: true;
47
+ retryAt?: Date;
48
+ waitMs?: number;
49
+ reason: RateLimitReason;
50
+ policy?: string;
51
+ source: RateLimitSource | "unknown";
52
+ module?: string;
53
+ scopeKey?: string;
54
+
55
+ static create(
56
+ options?: CreateRateLimitErrorParams
57
+ ): Promise<RateLimitError>;
58
+ }
59
+
60
+ type RateLimitErrorConstructor = FetchErrorConstructor & {
61
+ hint?: Partial<RateLimitHint>;
62
+ waitMs?: number;
63
+ module?: string;
64
+ scopeKey?: string;
65
+ now?: number;
66
+ };
67
+
68
+ type CreateRateLimitErrorParams = RateLimitErrorConstructor;
69
+
23
70
  type FetchErrorResponse = {
24
71
  headers?: object;
25
72
  status?: number;
@@ -1,5 +1,6 @@
1
1
  declare module "@friggframework/module-plugin" {
2
2
  import { Delegate, IFriggDelegate } from "@friggframework/core";
3
+ import type { RateLimitHint } from "@friggframework/errors";
3
4
 
4
5
  export interface Credential {
5
6
  id?: string;
@@ -22,8 +23,49 @@ declare module "@friggframework/module-plugin" {
22
23
  export type MappedEntity = Entity & { id: string; type: any };
23
24
 
24
25
 
26
+ export type RateLimitScope =
27
+ | "credential"
28
+ | "entity"
29
+ | "app"
30
+ | ((requester: Requester) => string | number | null | undefined);
31
+
32
+ export type RateLimitSignal = {
33
+ status?: number;
34
+ headers?: { get(name: string): string | null } | object;
35
+ body?: unknown;
36
+ };
37
+
38
+ export type RateLimitWindow = {
39
+ name: string;
40
+ limit?: number;
41
+ perMs?: number;
42
+ rollingMs?: number;
43
+ resets?: { at: string; tz: string };
44
+ };
45
+
46
+ export type RateLimitPolicy = {
47
+ scope?: RateLimitScope;
48
+ windows?: RateLimitWindow[];
49
+ maxConcurrency?: number;
50
+ minRetryAfterMs?: number;
51
+ parsers?: Array<"retryAfter" | "resetHeaders" | "ietf">;
52
+ classify?(
53
+ signal: RateLimitSignal
54
+ ): Partial<Omit<RateLimitHint, "source">> & {
55
+ source?: "header" | "body" | "static";
56
+ } | null | undefined;
57
+ userHints?: Record<
58
+ string,
59
+ { links?: Array<{ label: string; url: string }> }
60
+ >;
61
+ };
62
+
25
63
  export class Requester implements IFriggRequester {
64
+ static rateLimit?: RateLimitPolicy;
65
+ static requestTimeoutMs?: number;
66
+
26
67
  DLGT_INVALID_AUTH: string;
68
+ requestTimeoutMs: number;
27
69
  backOff: number[];
28
70
  fetch: any;
29
71
  isRefreshable: boolean;
@@ -87,6 +129,7 @@ declare module "@friggframework/module-plugin" {
87
129
  type RequesterConstructor = {
88
130
  backOff?: number[];
89
131
  fetch?: any;
132
+ random?: () => number;
90
133
  };
91
134
 
92
135
  export class ApiKeyRequester
@@ -23,7 +23,7 @@ class TestUserRepository {
23
23
 
24
24
  async createToken(userId, rawToken, minutes = 120) {
25
25
  const token = `token-for-${userId}-for-${minutes}-mins`;
26
- this.tokens.set(token, { id: token, userId, rawToken });
26
+ this.tokens.set(token, { user: userId, rawToken });
27
27
  return token;
28
28
  }
29
29
 
@@ -1,16 +1,13 @@
1
1
  const Boom = require('@hapi/boom');
2
- const { getLogger } = require('../../logs');
3
-
4
- const log = getLogger('frigg.user.authentication');
5
2
 
6
3
  /**
7
4
  * Use case for authenticating a user using multiple authentication strategies.
8
- *
5
+ *
9
6
  * Supports three authentication modes in priority order:
10
7
  * 1. Shared Secret (backend-to-backend with x-frigg-api-key + x-frigg headers)
11
8
  * 2. Adopter JWT (custom JWT authentication)
12
9
  * 3. Frigg Native Token (bearer token from /user/login)
13
- *
10
+ *
14
11
  * x-frigg-appUserId and x-frigg-appOrgId headers are automatically supported
15
12
  * for user identification with any auth mode. When present with JWT or Frigg
16
13
  * tokens, they are validated to match the authenticated user.
@@ -53,18 +50,12 @@ class AuthenticateUser {
53
50
  const authModes = this.userConfig.authModes || { friggToken: true };
54
51
  const appUserId = req.headers['x-frigg-appuserid'];
55
52
  const appOrgId = req.headers['x-frigg-apporgid'];
56
- log.debug('Request headers received', {
57
- eventName: `${log.name}.headers_received`,
58
- headerNames: Object.keys(req.headers),
59
- });
53
+ let user = null;
60
54
 
61
55
  // Priority 1: Shared Secret (backend-to-backend with API key)
62
56
  if (authModes.sharedSecret !== false) {
63
57
  const apiKey = req.headers['x-frigg-api-key'];
64
58
  if (apiKey) {
65
- log.debug('Attempting shared secret authentication', {
66
- eventName: `${log.name}.shared_secret_attempted`,
67
- });
68
59
  // Validate the API key (authentication)
69
60
  await this.authenticateWithSharedSecret.execute(apiKey);
70
61
  // Get user from x-frigg headers (authorization)
@@ -73,9 +64,6 @@ class AuthenticateUser {
73
64
  appOrgId
74
65
  );
75
66
  }
76
- log.debug('No x-frigg-api-key header, skipping shared secret', {
77
- eventName: `${log.name}.shared_secret_skipped`,
78
- });
79
67
  }
80
68
 
81
69
  // Priority 2: Adopter JWT (if enabled)
@@ -83,13 +71,10 @@ class AuthenticateUser {
83
71
  authModes.adopterJwt === true &&
84
72
  req.headers.authorization?.startsWith('Bearer ')
85
73
  ) {
86
- log.debug('Attempting adopter JWT authentication', {
87
- eventName: `${log.name}.adopter_jwt_attempted`,
88
- });
89
74
  const token = req.headers.authorization.split(' ')[1];
90
75
  // Detect JWT format (3 parts separated by dots)
91
76
  if (token && token.split('.').length === 3) {
92
- const user = await this.getUserFromAdopterJwt.execute(token);
77
+ user = await this.getUserFromAdopterJwt.execute(token);
93
78
  // Validate x-frigg headers match JWT claims if present
94
79
  if (appUserId || appOrgId) {
95
80
  this.validateUserMatch(user, appUserId, appOrgId);
@@ -100,10 +85,7 @@ class AuthenticateUser {
100
85
 
101
86
  // Priority 3: Frigg native token (default)
102
87
  if (authModes.friggToken !== false && req.headers.authorization) {
103
- log.debug('Attempting Frigg native token authentication', {
104
- eventName: `${log.name}.frigg_token_attempted`,
105
- });
106
- const user = await this.getUserFromBearerToken.execute(
88
+ user = await this.getUserFromBearerToken.execute(
107
89
  req.headers.authorization
108
90
  );
109
91
  // Validate x-frigg headers match token user if present
@@ -141,3 +123,5 @@ class AuthenticateUser {
141
123
  }
142
124
 
143
125
  module.exports = { AuthenticateUser };
126
+
127
+
@@ -40,13 +40,8 @@ class GetUserFromBearerToken {
40
40
  throw Boom.unauthorized('Session Token Not Found');
41
41
  }
42
42
 
43
- const tokenUserId = sessionToken.userId;
44
- if (!tokenUserId) {
45
- throw Boom.unauthorized('Session Token Has No User');
46
- }
47
-
48
43
  if (this.userConfig.primary === 'organization') {
49
- const organizationUserData = await this.userRepository.findOrganizationUserById(tokenUserId);
44
+ const organizationUserData = await this.userRepository.findOrganizationUserById(sessionToken.user);
50
45
 
51
46
  if (!organizationUserData) {
52
47
  throw Boom.unauthorized('Organization User Not Found');
@@ -62,7 +57,7 @@ class GetUserFromBearerToken {
62
57
  );
63
58
  }
64
59
 
65
- const individualUserData = await this.userRepository.findIndividualUserById(tokenUserId);
60
+ const individualUserData = await this.userRepository.findIndividualUserById(sessionToken.user);
66
61
 
67
62
  if (!individualUserData) {
68
63
  throw Boom.unauthorized('Individual User Not Found');
@@ -1,24 +0,0 @@
1
- /**
2
- * Recognises values produced by Cryptor.encrypt():
3
- * keyId:iv:ciphertext:encryptedKey
4
- * keyId and encryptedKey are base64, iv and ciphertext are hex, so all four
5
- * parts match the base64 alphabet. Real envelopes are well over 50
6
- * characters (the encrypted data key alone is longer).
7
- *
8
- * Shared by the Prisma (FieldEncryptionService) and DocumentDB paths so a
9
- * plaintext value that happens to contain colons (`a:b:c:d`, a URL with
10
- * userinfo and a port) is never mistaken for ciphertext: on write it gets
11
- * encrypted, on read it is returned as plaintext.
12
- */
13
- const BASE64_PART = /^[A-Za-z0-9+/=]+$/;
14
- const MIN_ENVELOPE_LENGTH = 50;
15
-
16
- function isEncryptedEnvelope(value) {
17
- if (typeof value !== 'string' || value.length < MIN_ENVELOPE_LENGTH) {
18
- return false;
19
- }
20
- const parts = value.split(':');
21
- return parts.length === 4 && parts.every((part) => BASE64_PART.test(part));
22
- }
23
-
24
- module.exports = { isEncryptedEnvelope };
@@ -1,14 +0,0 @@
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 };
@@ -1,92 +0,0 @@
1
- const {
2
- assertEntityIdsInput,
3
- integrationNotFound,
4
- loadIntegration,
5
- } = require('../utils/assert-entity-ids-input');
6
-
7
- /**
8
- * Attaches entities to an existing integration, e.g. when a user grants
9
- * access to more accounts after the integration was created. Every entity
10
- * must exist, belong to the integration's user, and be of a module the
11
- * integration already holds (so hydration can load it). Entities that are
12
- * already attached are left as they are.
13
- * @class AddEntitiesToIntegration
14
- */
15
- class AddEntitiesToIntegration {
16
- /**
17
- * @param {Object} params
18
- * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
19
- * @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
20
- */
21
- constructor({ integrationRepository, moduleRepository }) {
22
- this.integrationRepository = integrationRepository;
23
- this.moduleRepository = moduleRepository;
24
- }
25
-
26
- /**
27
- * @param {string} integrationId
28
- * @param {string[]} entityIds
29
- * @returns {Promise<Object>} The updated integration record.
30
- */
31
- async execute(integrationId, entityIds) {
32
- assertEntityIdsInput(integrationId, entityIds);
33
-
34
- const integration = await loadIntegration(
35
- this.integrationRepository,
36
- integrationId
37
- );
38
-
39
- const entities = await this.moduleRepository.findEntitiesByIds(
40
- entityIds
41
- );
42
- const foundIds = new Set(entities.map((e) => String(e.id)));
43
- const missing = entityIds.filter((id) => !foundIds.has(String(id)));
44
- if (missing.length > 0) {
45
- const error = new Error(
46
- `Entities not found: ${missing.join(', ')}`
47
- );
48
- error.code = 'ENTITIES_NOT_FOUND';
49
- throw error;
50
- }
51
-
52
- const foreign = entities.filter(
53
- (e) => String(e.userId) !== String(integration.userId)
54
- );
55
- if (foreign.length > 0) {
56
- const error = new Error(
57
- `Entities do not belong to the integration's user: ${foreign
58
- .map((e) => e.id)
59
- .join(', ')}`
60
- );
61
- error.code = 'ENTITY_USER_MISMATCH';
62
- throw error;
63
- }
64
-
65
- const attached = await this.moduleRepository.findEntitiesByIds(
66
- integration.entitiesIds ?? []
67
- );
68
- const heldModules = new Set(attached.map((e) => e.moduleName));
69
- const otherModules = entities.filter(
70
- (e) => !heldModules.has(e.moduleName)
71
- );
72
- if (otherModules.length > 0) {
73
- const error = new Error(
74
- `Entities belong to a module the integration does not hold: ${otherModules
75
- .map((e) => `${e.id} (${e.moduleName})`)
76
- .join(', ')}`
77
- );
78
- error.code = 'ENTITY_MODULE_MISMATCH';
79
- throw error;
80
- }
81
-
82
- const updated =
83
- await this.integrationRepository.addEntitiesToIntegration(
84
- integrationId,
85
- entityIds
86
- );
87
- if (!updated) throw integrationNotFound(integrationId);
88
- return updated;
89
- }
90
- }
91
-
92
- module.exports = { AddEntitiesToIntegration };
@@ -1,70 +0,0 @@
1
- const {
2
- assertEntityIdsInput,
3
- integrationNotFound,
4
- loadIntegration,
5
- } = require('../utils/assert-entity-ids-input');
6
-
7
- /**
8
- * Detaches entities from an integration. Entities that are not attached are
9
- * ignored, and detached entities are not deleted. Every module the
10
- * integration holds must keep at least one entity, so the integration can
11
- * still hydrate each of its modules.
12
- * @class RemoveEntitiesFromIntegration
13
- */
14
- class RemoveEntitiesFromIntegration {
15
- /**
16
- * @param {Object} params
17
- * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
18
- * @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
19
- */
20
- constructor({ integrationRepository, moduleRepository }) {
21
- this.integrationRepository = integrationRepository;
22
- this.moduleRepository = moduleRepository;
23
- }
24
-
25
- /**
26
- * @param {string} integrationId
27
- * @param {string[]} entityIds
28
- * @returns {Promise<Object>} The updated integration record.
29
- */
30
- async execute(integrationId, entityIds) {
31
- assertEntityIdsInput(integrationId, entityIds);
32
-
33
- const integration = await loadIntegration(
34
- this.integrationRepository,
35
- integrationId
36
- );
37
-
38
- const removing = new Set(entityIds.map(String));
39
- const attached = await this.moduleRepository.findEntitiesByIds(
40
- integration.entitiesIds ?? []
41
- );
42
- const emptied = [...new Set(attached.map((e) => e.moduleName))].filter(
43
- (moduleName) =>
44
- !attached.some(
45
- (e) =>
46
- e.moduleName === moduleName &&
47
- !removing.has(String(e.id))
48
- )
49
- );
50
- if (emptied.length > 0) {
51
- const error = new Error(
52
- `Removing these entities would leave no entity for module(s): ${emptied.join(
53
- ', '
54
- )}`
55
- );
56
- error.code = 'LAST_ENTITY_OF_MODULE';
57
- throw error;
58
- }
59
-
60
- const updated =
61
- await this.integrationRepository.removeEntitiesFromIntegration(
62
- integrationId,
63
- entityIds
64
- );
65
- if (!updated) throw integrationNotFound(integrationId);
66
- return updated;
67
- }
68
- }
69
-
70
- module.exports = { RemoveEntitiesFromIntegration };
@@ -1,42 +0,0 @@
1
- /**
2
- * Throws INVALID_INTEGRATION_DATA unless an integration id and a non-empty
3
- * list of entity ids are given.
4
- * @param {string} integrationId
5
- * @param {string[]} entityIds
6
- */
7
- function assertEntityIdsInput(integrationId, entityIds) {
8
- if (!integrationId || !Array.isArray(entityIds) || entityIds.length === 0) {
9
- const error = new Error(
10
- 'integrationId and a non-empty entityIds array are required'
11
- );
12
- error.code = 'INVALID_INTEGRATION_DATA';
13
- throw error;
14
- }
15
- }
16
-
17
- function integrationNotFound(integrationId) {
18
- const error = new Error(`Integration ${integrationId} not found`);
19
- error.code = 'INTEGRATION_NOT_FOUND';
20
- return error;
21
- }
22
-
23
- /**
24
- * Loads an integration, mapping the repositories' "not found" error to
25
- * INTEGRATION_NOT_FOUND. Any other failure (connection, invalid id) is
26
- * rethrown unchanged.
27
- * @param {Object} integrationRepository
28
- * @param {string} integrationId
29
- * @returns {Promise<Object>} The integration record.
30
- */
31
- async function loadIntegration(integrationRepository, integrationId) {
32
- try {
33
- return await integrationRepository.findIntegrationById(integrationId);
34
- } catch (error) {
35
- if (/^Integration with id .* not found$/.test(error?.message)) {
36
- throw integrationNotFound(integrationId);
37
- }
38
- throw error;
39
- }
40
- }
41
-
42
- module.exports = { assertEntityIdsInput, integrationNotFound, loadIntegration };
package/jest.db.config.js DELETED
@@ -1,23 +0,0 @@
1
- /*
2
- * Database integration suites (`*.db.test.js`).
3
- *
4
- * These talk to real databases instead of mocking Prisma, so they are kept
5
- * out of the default `npm test` run and executed with `npm run test:db`.
6
- * They need generated Prisma clients (`npm run prisma:generate`) and:
7
- * - a MongoDB replica set (Prisma requires one for MongoDB writes):
8
- * FRIGG_TEST_MONGODB_URL, default
9
- * mongodb://localhost:27017/frigg?replicaSet=rs0
10
- * - PostgreSQL with the prisma-postgresql migrations applied:
11
- * FRIGG_TEST_POSTGRES_URL, default
12
- * postgresql://postgres:postgres@localhost:5432/frigg?schema=public
13
- * The repository parity suites skip themselves unless their own URLs are
14
- * set (INTEGRATION_ENTITIES_PARITY_* / QUERY_MAPPINGS_PARITY_*).
15
- */
16
- const base = require('./jest.config');
17
-
18
- module.exports = {
19
- ...base,
20
- coverageThreshold: undefined,
21
- testMatch: ['**/*.db.test.js'],
22
- testPathIgnorePatterns: ['/node_modules/'],
23
- };