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

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