@mondaydotcomorg/monday-authorization 3.5.1 → 3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-127d99a

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 (124) hide show
  1. package/dist/authorization-attributes-ms-service.d.ts +90 -0
  2. package/dist/authorization-attributes-ms-service.d.ts.map +1 -0
  3. package/dist/authorization-attributes-ms-service.js +351 -0
  4. package/dist/authorization-attributes-service.d.ts +26 -47
  5. package/dist/authorization-attributes-service.d.ts.map +1 -1
  6. package/dist/authorization-attributes-service.js +33 -171
  7. package/dist/authorization-attributes-sns-service.d.ts +90 -0
  8. package/dist/authorization-attributes-sns-service.d.ts.map +1 -0
  9. package/dist/authorization-attributes-sns-service.js +217 -0
  10. package/dist/authorization-middleware.d.ts +2 -2
  11. package/dist/authorization-middleware.d.ts.map +1 -1
  12. package/dist/authorization-service.d.ts +3 -3
  13. package/dist/authorization-service.d.ts.map +1 -1
  14. package/dist/base-attribute-assignment.d.ts +18 -0
  15. package/dist/base-attribute-assignment.d.ts.map +1 -0
  16. package/dist/base-attribute-assignment.js +43 -0
  17. package/dist/constants/sns.d.ts +12 -2
  18. package/dist/constants/sns.d.ts.map +1 -1
  19. package/dist/constants/sns.js +22 -2
  20. package/dist/entity-attribute-assignment.d.ts +14 -0
  21. package/dist/entity-attribute-assignment.d.ts.map +1 -0
  22. package/dist/entity-attribute-assignment.js +24 -0
  23. package/dist/entity-attributes-constants.d.ts +7 -0
  24. package/dist/entity-attributes-constants.d.ts.map +1 -0
  25. package/dist/entity-attributes-constants.js +9 -0
  26. package/dist/errors/argument-error.d.ts +4 -0
  27. package/dist/errors/argument-error.d.ts.map +1 -0
  28. package/dist/errors/argument-error.js +11 -0
  29. package/dist/esm/authorization-attributes-ms-service.d.ts +90 -0
  30. package/dist/esm/authorization-attributes-ms-service.d.ts.map +1 -0
  31. package/dist/esm/authorization-attributes-ms-service.mjs +349 -0
  32. package/dist/esm/authorization-attributes-service.d.ts +26 -47
  33. package/dist/esm/authorization-attributes-service.d.ts.map +1 -1
  34. package/dist/esm/authorization-attributes-service.mjs +33 -167
  35. package/dist/esm/authorization-attributes-sns-service.d.ts +90 -0
  36. package/dist/esm/authorization-attributes-sns-service.d.ts.map +1 -0
  37. package/dist/esm/authorization-attributes-sns-service.mjs +211 -0
  38. package/dist/esm/authorization-middleware.d.ts +2 -2
  39. package/dist/esm/authorization-middleware.d.ts.map +1 -1
  40. package/dist/esm/authorization-service.d.ts +3 -3
  41. package/dist/esm/authorization-service.d.ts.map +1 -1
  42. package/dist/esm/base-attribute-assignment.d.ts +18 -0
  43. package/dist/esm/base-attribute-assignment.d.ts.map +1 -0
  44. package/dist/esm/base-attribute-assignment.mjs +41 -0
  45. package/dist/esm/constants/sns.d.ts +12 -2
  46. package/dist/esm/constants/sns.d.ts.map +1 -1
  47. package/dist/esm/constants/sns.mjs +17 -3
  48. package/dist/esm/entity-attribute-assignment.d.ts +14 -0
  49. package/dist/esm/entity-attribute-assignment.d.ts.map +1 -0
  50. package/dist/esm/entity-attribute-assignment.mjs +22 -0
  51. package/dist/esm/entity-attributes-constants.d.ts +7 -0
  52. package/dist/esm/entity-attributes-constants.d.ts.map +1 -0
  53. package/dist/esm/entity-attributes-constants.mjs +7 -0
  54. package/dist/esm/errors/argument-error.d.ts +4 -0
  55. package/dist/esm/errors/argument-error.d.ts.map +1 -0
  56. package/dist/esm/errors/argument-error.mjs +9 -0
  57. package/dist/esm/index.d.ts +9 -0
  58. package/dist/esm/index.d.ts.map +1 -1
  59. package/dist/esm/index.mjs +7 -0
  60. package/dist/esm/prometheus-service.d.ts +1 -2
  61. package/dist/esm/prometheus-service.d.ts.map +1 -1
  62. package/dist/esm/resource-attribute-assignment.d.ts +24 -0
  63. package/dist/esm/resource-attribute-assignment.d.ts.map +1 -0
  64. package/dist/esm/resource-attribute-assignment.mjs +34 -0
  65. package/dist/esm/resource-attributes-constants.d.ts +15 -0
  66. package/dist/esm/resource-attributes-constants.d.ts.map +1 -0
  67. package/dist/esm/resource-attributes-constants.mjs +25 -0
  68. package/dist/esm/testKit/index.d.ts +4 -4
  69. package/dist/esm/testKit/index.d.ts.map +1 -1
  70. package/dist/esm/types/authorization-attributes-contracts.d.ts +27 -12
  71. package/dist/esm/types/authorization-attributes-contracts.d.ts.map +1 -1
  72. package/dist/esm/types/authorization-attributes-contracts.mjs +6 -6
  73. package/dist/esm/types/authorization-attributes-service.interface.d.ts +56 -0
  74. package/dist/esm/types/authorization-attributes-service.interface.d.ts.map +1 -0
  75. package/dist/esm/types/authorization-attributes-service.interface.mjs +1 -0
  76. package/dist/esm/types/general.d.ts +1 -2
  77. package/dist/esm/types/general.d.ts.map +1 -1
  78. package/dist/esm/utils/validation.d.ts +45 -0
  79. package/dist/esm/utils/validation.d.ts.map +1 -0
  80. package/dist/esm/utils/validation.mjs +117 -0
  81. package/dist/index.d.ts +9 -0
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +15 -0
  84. package/dist/prometheus-service.d.ts +1 -2
  85. package/dist/prometheus-service.d.ts.map +1 -1
  86. package/dist/resource-attribute-assignment.d.ts +24 -0
  87. package/dist/resource-attribute-assignment.d.ts.map +1 -0
  88. package/dist/resource-attribute-assignment.js +36 -0
  89. package/dist/resource-attributes-constants.d.ts +15 -0
  90. package/dist/resource-attributes-constants.d.ts.map +1 -0
  91. package/dist/resource-attributes-constants.js +28 -0
  92. package/dist/testKit/index.d.ts +4 -4
  93. package/dist/testKit/index.d.ts.map +1 -1
  94. package/dist/types/authorization-attributes-contracts.d.ts +27 -12
  95. package/dist/types/authorization-attributes-contracts.d.ts.map +1 -1
  96. package/dist/types/authorization-attributes-contracts.js +5 -5
  97. package/dist/types/authorization-attributes-service.interface.d.ts +56 -0
  98. package/dist/types/authorization-attributes-service.interface.d.ts.map +1 -0
  99. package/dist/types/authorization-attributes-service.interface.js +1 -0
  100. package/dist/types/general.d.ts +1 -2
  101. package/dist/types/general.d.ts.map +1 -1
  102. package/dist/utils/validation.d.ts +45 -0
  103. package/dist/utils/validation.d.ts.map +1 -0
  104. package/dist/utils/validation.js +119 -0
  105. package/package.json +3 -2
  106. package/src/authorization-attributes-ms-service.ts +513 -0
  107. package/src/authorization-attributes-service.ts +35 -222
  108. package/src/authorization-attributes-sns-service.ts +312 -0
  109. package/src/authorization-middleware.ts +2 -2
  110. package/src/authorization-service.ts +4 -4
  111. package/src/base-attribute-assignment.ts +55 -0
  112. package/src/constants/sns.ts +19 -2
  113. package/src/entity-attribute-assignment.ts +21 -0
  114. package/src/entity-attributes-constants.ts +7 -0
  115. package/src/errors/argument-error.ts +7 -0
  116. package/src/index.ts +9 -0
  117. package/src/prometheus-service.ts +1 -3
  118. package/src/resource-attribute-assignment.ts +43 -0
  119. package/src/resource-attributes-constants.ts +35 -0
  120. package/src/testKit/index.ts +5 -5
  121. package/src/types/authorization-attributes-contracts.ts +36 -11
  122. package/src/types/authorization-attributes-service.interface.ts +101 -0
  123. package/src/types/general.ts +3 -2
  124. package/src/utils/validation.ts +114 -0
@@ -0,0 +1,119 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const zod = require('zod');
4
+ const errors_argumentError = require('../errors/argument-error.js');
5
+
6
+ /**
7
+ * Utility class for common validation operations using Zod
8
+ */
9
+ class ValidationUtils {
10
+ /**
11
+ * Validates that a value is an integer
12
+ * @param value The value to validate
13
+ * @param fieldName The name of the field for error messages
14
+ * @throws ArgumentError if value is not an integer
15
+ */
16
+ static validateInteger(value, fieldName) {
17
+ const schema = zod.z.number().int();
18
+ try {
19
+ schema.parse(value);
20
+ }
21
+ catch (error) {
22
+ if (error instanceof zod.z.ZodError) {
23
+ throw new errors_argumentError.ArgumentError(`${fieldName} must be an integer, got: ${value}`);
24
+ }
25
+ throw error;
26
+ }
27
+ }
28
+ /**
29
+ * Validates that a value is a non-empty string
30
+ * @param value The value to validate
31
+ * @param fieldName The name of the field for error messages
32
+ * @throws ArgumentError if value is not a string or is empty
33
+ */
34
+ static validateString(value, fieldName) {
35
+ const schema = zod.z.string().min(1);
36
+ try {
37
+ schema.parse(value);
38
+ }
39
+ catch (error) {
40
+ if (error instanceof zod.z.ZodError) {
41
+ if (typeof value !== 'string') {
42
+ throw new errors_argumentError.ArgumentError(`${fieldName} must be a string, got: ${typeof value}`);
43
+ }
44
+ throw new errors_argumentError.ArgumentError(`${fieldName} must be a non-empty string`);
45
+ }
46
+ throw error;
47
+ }
48
+ }
49
+ /**
50
+ * Validates that a value is an array and optionally checks minimum length
51
+ * @param value The value to validate
52
+ * @param fieldName The name of the field for error messages
53
+ * @param minLength Minimum required length (default: 0)
54
+ * @returns The validated array
55
+ * @throws ArgumentError if value is not an array or doesn't meet minimum length
56
+ */
57
+ static validateArray(value, fieldName, minLength = 0) {
58
+ const schema = zod.z.array(zod.z.any()).min(minLength);
59
+ try {
60
+ return schema.parse(value);
61
+ }
62
+ catch (error) {
63
+ if (error instanceof zod.z.ZodError) {
64
+ if (!Array.isArray(value)) {
65
+ throw new errors_argumentError.ArgumentError(`${fieldName} must be an array`);
66
+ }
67
+ throw new errors_argumentError.ArgumentError(`${fieldName} must have at least ${minLength} items`);
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+ /**
73
+ * Validates that a value is one of the allowed enum values
74
+ * @param value The value to validate
75
+ * @param validValues Array of valid values
76
+ * @param fieldName The name of the field for error messages
77
+ * @returns The validated value as the enum type
78
+ * @throws ArgumentError if value is not in validValues
79
+ */
80
+ static validateEnum(value, validValues, fieldName) {
81
+ const schema = zod.z.enum(validValues);
82
+ try {
83
+ return schema.parse(value);
84
+ }
85
+ catch (error) {
86
+ if (error instanceof zod.z.ZodError) {
87
+ throw new errors_argumentError.ArgumentError(`${fieldName} must be one of [${validValues.join(', ')}], got: ${value}`);
88
+ }
89
+ throw error;
90
+ }
91
+ }
92
+ /**
93
+ * Validates that all items in an array are strings
94
+ * @param value Array to validate
95
+ * @param fieldName The name of the field for error messages
96
+ * @throws ArgumentError if any item is not a string
97
+ */
98
+ static validateStringArray(value, fieldName) {
99
+ const schema = zod.z.array(zod.z.string());
100
+ try {
101
+ schema.parse(value);
102
+ }
103
+ catch (error) {
104
+ if (error instanceof zod.z.ZodError) {
105
+ const zodError = error;
106
+ const firstError = zodError.issues[0];
107
+ // Check if it's an array item validation error
108
+ if (firstError.path.length > 0 && typeof firstError.path[0] === 'number') {
109
+ const index = firstError.path[0];
110
+ throw new errors_argumentError.ArgumentError(`All ${fieldName} must be strings, but item at index ${index} is not`);
111
+ }
112
+ throw new errors_argumentError.ArgumentError(`${fieldName} must be an array`);
113
+ }
114
+ throw error;
115
+ }
116
+ }
117
+ }
118
+
119
+ exports.ValidationUtils = ValidationUtils;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mondaydotcomorg/monday-authorization",
3
- "version": "3.5.1",
3
+ "version": "3.5.3-feat-shaime-support-entity-attributes-in-authorization-sdk-127d99a",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "BSD-3-Clause",
@@ -31,7 +31,8 @@
31
31
  "lodash": "^4.17.21",
32
32
  "node-fetch": "^2.6.7",
33
33
  "on-headers": "^1.0.2",
34
- "ts-node": "^10.0.0"
34
+ "ts-node": "^10.0.0",
35
+ "zod": "^4.1.13"
35
36
  },
36
37
  "devDependencies": {
37
38
  "@mondaydotcomorg/trident-library": "^1.1.44",
@@ -0,0 +1,513 @@
1
+ import { Api, HttpClient } from '@mondaydotcomorg/trident-backend-api';
2
+ import { signAuthorizationHeader } from '@mondaydotcomorg/monday-jwt';
3
+ import { z } from 'zod';
4
+ import { ResourceAttributeAssignment } from './resource-attribute-assignment';
5
+ import { EntityAttributeAssignment } from './entity-attribute-assignment';
6
+ import {
7
+ AttributeOperation,
8
+ EntityType,
9
+ ResourceAttributeOperation,
10
+ EntityAttributeOperation,
11
+ } from './types/authorization-attributes-contracts';
12
+ import { ArgumentError } from './errors/argument-error';
13
+ import { AuthorizationInternalService, logger } from './authorization-internal-service';
14
+ import { getAttributionsFromApi } from './attributions-service';
15
+ import { APP_NAME } from './constants';
16
+ import { ValidationUtils } from './utils/validation';
17
+ import { IAuthorizationAttributesService } from './types/authorization-attributes-service.interface';
18
+ import { Resource } from './types/general';
19
+ const INTERNAL_APP_NAME = 'internal_ms';
20
+ const UPSERT_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource';
21
+ const DELETE_RESOURCE_ATTRIBUTES_PATH = '/attributes/{accountId}/resource/{resourceType}/{resourceId}';
22
+ const UPSERT_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity';
23
+ const DELETE_ENTITY_ATTRIBUTES_PATH = '/attributes/{accountId}/entity/{entityType}/{entityId}';
24
+
25
+ interface DeleteRequestBody {
26
+ keys: string[];
27
+ }
28
+
29
+ /**
30
+ * Service class for managing resource attributes in the authorization microservice.
31
+ * Provides synchronous HTTP operations to create/update and delete attributes on resources.
32
+ */
33
+ export class AuthorizationAttributesMsService implements IAuthorizationAttributesService {
34
+ private static LOG_TAG = 'authorization_attributes_ms';
35
+ private static httpClient: HttpClient | undefined = Api.getPart('httpClient');
36
+ /**
37
+ * Creates or updates resource attributes synchronously.
38
+ * @param accountId The account ID
39
+ * @param resourceAttributeAssignments Array of ResourceAttributeAssignment objects
40
+ * @returns Promise<void>
41
+ */
42
+ async upsertResourceAttributes(
43
+ accountId: number,
44
+ resourceAttributeAssignments: ResourceAttributeAssignment[],
45
+ _appName?: string,
46
+ _callerActionIdentifier?: string
47
+ ): Promise<void> {
48
+ return AuthorizationAttributesMsService.executeUpsertRequest(
49
+ accountId,
50
+ resourceAttributeAssignments,
51
+ UPSERT_RESOURCE_ATTRIBUTES_PATH,
52
+ 'resourceAttributeAssignments',
53
+ ResourceAttributeAssignment,
54
+ 'resource',
55
+ 'upsertResourceAttributesSync'
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Deletes specific attributes from a resource synchronously.
61
+ * @param accountId The account ID
62
+ * @param resource Object with resourceType (string) and resourceId (number)
63
+ * @param attributeKeys Array of attribute key strings to delete
64
+ * @returns Promise<void>
65
+ */
66
+ async deleteResourceAttributes(
67
+ accountId: number,
68
+ resource: Resource,
69
+ attributeKeys: string[],
70
+ _appName?: string,
71
+ _callerActionIdentifier?: string
72
+ ): Promise<void> {
73
+ // Validate resource object
74
+ if (!resource || typeof resource !== 'object') {
75
+ throw new ArgumentError('resource must be an object');
76
+ }
77
+ if (!resource.id) {
78
+ throw new ArgumentError('resource.id is required');
79
+ }
80
+ ValidationUtils.validateInteger(resource.id, 'resource.id');
81
+ ValidationUtils.validateString(resource.type, 'resource.type');
82
+
83
+ return AuthorizationAttributesMsService.executeDeleteRequest(
84
+ accountId,
85
+ DELETE_RESOURCE_ATTRIBUTES_PATH,
86
+ {
87
+ resourceType: resource.type,
88
+ resourceId: resource.id,
89
+ },
90
+ attributeKeys,
91
+ 'resource',
92
+ 'deleteResourceAttributesSync',
93
+ { resource }
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Creates or updates entity attributes synchronously.
99
+ * @param accountId The account ID
100
+ * @param entityAttributeAssignments Array of EntityAttributeAssignment objects
101
+ * @returns Promise<void>
102
+ */
103
+ async upsertEntityAttributes(
104
+ accountId: number,
105
+ entityAttributeAssignments: EntityAttributeAssignment[],
106
+ _appName?: string,
107
+ _callerActionIdentifier?: string
108
+ ): Promise<void> {
109
+ return AuthorizationAttributesMsService.executeUpsertRequest(
110
+ accountId,
111
+ entityAttributeAssignments,
112
+ UPSERT_ENTITY_ATTRIBUTES_PATH,
113
+ 'entityAttributeAssignments',
114
+ EntityAttributeAssignment,
115
+ 'entity',
116
+ 'upsertEntityAttributesSync'
117
+ );
118
+ }
119
+
120
+ /**
121
+ * Deletes specific attributes from an entity synchronously.
122
+ * @param accountId The account ID
123
+ * @param entityType The entity type
124
+ * @param entityId The entity ID
125
+ * @param attributeKeys Array of attribute key strings to delete
126
+ * @returns Promise<void>
127
+ */
128
+ async deleteEntityAttributes(
129
+ accountId: number,
130
+ entityType: EntityType | string,
131
+ entityId: number,
132
+ attributeKeys: string[],
133
+ _appName?: string,
134
+ _callerActionIdentifier?: string
135
+ ): Promise<void> {
136
+ if (!entityType || typeof entityType !== 'string' || entityType.trim() === '') {
137
+ throw new ArgumentError(`entityType must be a non-empty string, got: ${entityType}`);
138
+ }
139
+ ValidationUtils.validateInteger(entityId, 'entityId');
140
+
141
+ return AuthorizationAttributesMsService.executeDeleteRequest(
142
+ accountId,
143
+ DELETE_ENTITY_ATTRIBUTES_PATH,
144
+ {
145
+ entityType,
146
+ entityId,
147
+ },
148
+ attributeKeys,
149
+ 'entity',
150
+ 'deleteEntityAttributesSync',
151
+ { entityType, entityId }
152
+ );
153
+ }
154
+
155
+ /**
156
+ * Updates resource attributes (batch operations).
157
+ * Note: MS service does not support batch operations directly.
158
+ * This method processes operations sequentially using upsert/delete methods.
159
+ * @param accountId The account ID
160
+ * @param appName App name (required for interface compatibility, but not used in MS service)
161
+ * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
162
+ * @param resourceAttributeOperations Array of operations to perform
163
+ * @returns Promise<ResourceAttributesOperation[]> Array of processed operations
164
+ */
165
+ async updateResourceAttributes(
166
+ accountId: number,
167
+ _appName: string,
168
+ _callerActionIdentifier: string,
169
+ resourceAttributeOperations: ResourceAttributeOperation[]
170
+ ): Promise<ResourceAttributeOperation[]> {
171
+ const processedOperations: ResourceAttributeOperation[] = [];
172
+
173
+ for (const operation of resourceAttributeOperations) {
174
+ if (operation.operationType === AttributeOperation.UPSERT) {
175
+ if (!operation.resourceId) {
176
+ throw new ArgumentError('resourceId is required for upsert operation');
177
+ }
178
+ await this.upsertResourceAttributes(accountId, [
179
+ new ResourceAttributeAssignment(
180
+ operation.resourceId,
181
+ operation.resourceType,
182
+ operation.key,
183
+ operation.value || ''
184
+ ),
185
+ ]);
186
+ processedOperations.push(operation);
187
+ } else if (operation.operationType === AttributeOperation.DELETE) {
188
+ if (!operation.resourceId) {
189
+ throw new ArgumentError('resourceId is required for delete operation');
190
+ }
191
+ await this.deleteResourceAttributes(
192
+ accountId,
193
+ {
194
+ type: operation.resourceType,
195
+ id: operation.resourceId,
196
+ },
197
+ [operation.key]
198
+ );
199
+ processedOperations.push(operation);
200
+ }
201
+ }
202
+
203
+ return processedOperations;
204
+ }
205
+
206
+ /**
207
+ * Updates entity attributes (batch operations).
208
+ * Note: MS service does not support batch operations directly.
209
+ * This method processes operations sequentially using upsert/delete methods.
210
+ * @param accountId The account ID
211
+ * @param appName App name (required for interface compatibility, but not used in MS service)
212
+ * @param callerActionIdentifier Action identifier (required for interface compatibility, but not used in MS service)
213
+ * @param entityAttributeOperations Array of operations to perform
214
+ * @returns Promise<EntityAttributesOperation[]> Array of processed operations
215
+ */
216
+ async updateEntityAttributes(
217
+ accountId: number,
218
+ _appName: string,
219
+ _callerActionIdentifier: string,
220
+ entityAttributeOperations: EntityAttributeOperation[]
221
+ ): Promise<EntityAttributeOperation[]> {
222
+ const processedOperations: EntityAttributeOperation[] = [];
223
+ for (const operation of entityAttributeOperations) {
224
+ if (operation.operationType === 'upsert') {
225
+ await this.upsertEntityAttributes(accountId, [
226
+ new EntityAttributeAssignment(operation.entityId, operation.entityType, operation.key, operation.value || ''),
227
+ ]);
228
+ processedOperations.push(operation);
229
+ } else if (operation.operationType === 'delete') {
230
+ await this.deleteEntityAttributes(accountId, operation.entityType, operation.entityId, [operation.key]);
231
+ processedOperations.push(operation);
232
+ }
233
+ }
234
+
235
+ return processedOperations;
236
+ }
237
+
238
+ /**
239
+ * Replaces path template parameters with actual values
240
+ * @param template Path template with placeholders like {accountId}
241
+ * @param params Object with parameter names and values
242
+ * @returns Path with all placeholders replaced
243
+ */
244
+ private static replacePathParams(template: string, params: Record<string, string | number>): string {
245
+ let path = template;
246
+ for (const [key, value] of Object.entries(params)) {
247
+ path = path.replace(`{${key}}`, String(value));
248
+ }
249
+ return path;
250
+ }
251
+
252
+ /**
253
+ * Generic helper for executing delete requests
254
+ */
255
+ private static async executeDeleteRequest(
256
+ accountId: number,
257
+ pathTemplate: string,
258
+ pathParams: Record<string, string | number>,
259
+ keys: string[],
260
+ logPrefix: string,
261
+ methodName: string,
262
+ context: Record<string, any> = {}
263
+ ): Promise<void> {
264
+ // Validate inputs
265
+ ValidationUtils.validateInteger(accountId, 'accountId');
266
+ ValidationUtils.validateArray(keys, 'attributeKeys');
267
+
268
+ if (!keys.length) {
269
+ logger.warn({ tag: this.LOG_TAG, accountId, ...pathParams }, `${methodName} called with empty keys array`);
270
+ return;
271
+ }
272
+
273
+ // Validate all keys are strings
274
+ ValidationUtils.validateStringArray(keys, 'attributeKeys');
275
+
276
+ // Build request body
277
+ const requestBody: DeleteRequestBody = {
278
+ keys,
279
+ };
280
+
281
+ if (!AuthorizationAttributesMsService.httpClient) {
282
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
283
+ }
284
+ const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId, ...pathParams });
285
+ const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
286
+
287
+ try {
288
+ logger.info(
289
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys },
290
+ `Deleting ${logPrefix} attributes`
291
+ );
292
+
293
+ await AuthorizationAttributesMsService.httpClient.fetch(
294
+ {
295
+ url: {
296
+ appName: APP_NAME,
297
+ path,
298
+ },
299
+ method: 'DELETE',
300
+ headers,
301
+ body: JSON.stringify(requestBody),
302
+ },
303
+ {
304
+ timeout: AuthorizationInternalService.getRequestTimeout(),
305
+ retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
306
+ }
307
+ );
308
+
309
+ logger.info(
310
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, ...pathParams, keys },
311
+ `Successfully deleted ${logPrefix} attributes`
312
+ );
313
+ } catch (err) {
314
+ logger.error(
315
+ {
316
+ tag: AuthorizationAttributesMsService.LOG_TAG,
317
+ method: methodName,
318
+ accountId,
319
+ ...pathParams,
320
+ ...context,
321
+ error: err instanceof Error ? err.message : String(err),
322
+ },
323
+ `Failed in ${methodName}`
324
+ );
325
+ throw err;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Gets request headers including Authorization, Content-Type, and optional attribution headers
331
+ */
332
+ private static getRequestHeaders(accountId: number, userId?: number): Record<string, string> {
333
+ const headers: Record<string, string> = {
334
+ 'Content-Type': 'application/json',
335
+ };
336
+
337
+ // Generate Authorization token
338
+ const authToken = signAuthorizationHeader({
339
+ appName: INTERNAL_APP_NAME,
340
+ accountId,
341
+ userId,
342
+ });
343
+ headers.Authorization = authToken;
344
+
345
+ // Add attribution headers if available
346
+ const attributionHeaders = getAttributionsFromApi();
347
+ for (const key in attributionHeaders) {
348
+ if (Object.prototype.hasOwnProperty.call(attributionHeaders, key)) {
349
+ headers[key] = attributionHeaders[key];
350
+ }
351
+ }
352
+
353
+ // Add X-REQUEST-ID if available from context
354
+ try {
355
+ const tridentContext = Api.getPart('context');
356
+ if (tridentContext?.runtimeAttributions) {
357
+ const outgoingHeaders = tridentContext.runtimeAttributions.buildOutgoingHeaders('HTTP_INTERNAL');
358
+ if (outgoingHeaders) {
359
+ const attributionHeadersMap: Record<string, string> = {};
360
+ for (const [key, value] of outgoingHeaders) {
361
+ attributionHeadersMap[key] = value;
362
+ }
363
+ if (attributionHeadersMap['x-request-id']) {
364
+ headers['X-REQUEST-ID'] = attributionHeadersMap['x-request-id'];
365
+ }
366
+ }
367
+ }
368
+ } catch (error) {
369
+ // Silently fail if context is not available
370
+ logger.debug({ tag: AuthorizationAttributesMsService.LOG_TAG, error }, 'Failed to get request ID from context');
371
+ }
372
+
373
+ // Add X-REQUEST-START timestamp
374
+ headers['X-REQUEST-START'] = Math.floor(Date.now() / 1000).toString();
375
+
376
+ return headers;
377
+ }
378
+
379
+ /**
380
+ * Validates that all messages are instances of the specified message class
381
+ */
382
+ private static validateMessages<T>(attributesMessages: T[], messageClass: abstract new (...args: any[]) => T): void {
383
+ // Validate messageClass is a function using Zod
384
+ const classSchema = z.custom<abstract new (...args: any[]) => T>(value => typeof value === 'function', {
385
+ message: 'messageClass must be a class/constructor function',
386
+ });
387
+
388
+ try {
389
+ classSchema.parse(messageClass);
390
+ } catch (error) {
391
+ if (error instanceof z.ZodError) {
392
+ const firstError = error.issues[0];
393
+ throw new ArgumentError(firstError.message);
394
+ }
395
+ throw error;
396
+ }
397
+
398
+ const className = messageClass.name || 'ResourceAttributeAssignment';
399
+
400
+ // First validate it's an array
401
+ ValidationUtils.validateArray(attributesMessages, 'attributesMessages');
402
+
403
+ // Then use Zod to validate each item is an instance of the class
404
+ const schema = z.array(z.any()).refine(
405
+ items => {
406
+ for (let i = 0; i < items.length; i++) {
407
+ if (!(items[i] instanceof messageClass)) {
408
+ return false;
409
+ }
410
+ }
411
+ return true;
412
+ },
413
+ {
414
+ message: `All attributesMessages must be instances of ${className}`,
415
+ }
416
+ );
417
+
418
+ try {
419
+ schema.parse(attributesMessages);
420
+ } catch (error) {
421
+ if (error instanceof z.ZodError) {
422
+ // Find the first invalid index for a more specific error message
423
+ const invalidIndex = attributesMessages.findIndex(item => !(item instanceof messageClass));
424
+ if (invalidIndex !== -1) {
425
+ throw new ArgumentError(
426
+ `All attributesMessages must be instances of ${className}, but item at index ${invalidIndex} is not`
427
+ );
428
+ }
429
+ const firstError = error.issues[0];
430
+ throw new ArgumentError(firstError.message);
431
+ }
432
+ throw error;
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Generic helper for executing upsert requests
438
+ */
439
+ private static async executeUpsertRequest<T extends ResourceAttributeAssignment | EntityAttributeAssignment>(
440
+ accountId: number,
441
+ assignments: T[],
442
+ pathTemplate: string,
443
+ requestBodyKey: 'resourceAttributeAssignments' | 'entityAttributeAssignments',
444
+ assignmentClass: abstract new (...args: any[]) => T,
445
+ logPrefix: string,
446
+ methodName: string
447
+ ): Promise<void> {
448
+ // Validate inputs
449
+ ValidationUtils.validateInteger(accountId, 'accountId');
450
+ ValidationUtils.validateArray(assignments, 'assignments');
451
+
452
+ if (!assignments.length) {
453
+ logger.warn(
454
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId },
455
+ `${methodName} called with empty array`
456
+ );
457
+ return;
458
+ }
459
+
460
+ // Validate all assignments are instances of the correct class
461
+ AuthorizationAttributesMsService.validateMessages(assignments, assignmentClass);
462
+
463
+ const requestBody =
464
+ requestBodyKey === 'resourceAttributeAssignments'
465
+ ? { resourceAttributeAssignments: assignments }
466
+ : { entityAttributeAssignments: assignments };
467
+
468
+ if (!AuthorizationAttributesMsService.httpClient) {
469
+ throw new Error('AuthorizationAttributesMsService: HTTP client is not initialized');
470
+ }
471
+ const path = AuthorizationAttributesMsService.replacePathParams(pathTemplate, { accountId });
472
+ const headers = AuthorizationAttributesMsService.getRequestHeaders(accountId);
473
+
474
+ try {
475
+ logger.info(
476
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length },
477
+ `Upserting ${logPrefix} attributes`
478
+ );
479
+
480
+ await AuthorizationAttributesMsService.httpClient.fetch(
481
+ {
482
+ url: {
483
+ appName: APP_NAME,
484
+ path,
485
+ },
486
+ method: 'POST',
487
+ headers,
488
+ body: JSON.stringify(requestBody),
489
+ },
490
+ {
491
+ timeout: AuthorizationInternalService.getRequestTimeout(),
492
+ retryPolicy: AuthorizationInternalService.getRetriesPolicy(),
493
+ }
494
+ );
495
+
496
+ logger.debug(
497
+ { tag: AuthorizationAttributesMsService.LOG_TAG, accountId, count: assignments.length },
498
+ `Successfully upserted ${logPrefix} attributes`
499
+ );
500
+ } catch (err) {
501
+ logger.error(
502
+ {
503
+ tag: AuthorizationAttributesMsService.LOG_TAG,
504
+ method: methodName,
505
+ accountId,
506
+ error: err instanceof Error ? err.message : String(err),
507
+ },
508
+ `Failed in ${methodName}`
509
+ );
510
+ throw err;
511
+ }
512
+ }
513
+ }