@uipath/uipath-typescript 1.3.11 → 1.4.1

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 (59) hide show
  1. package/dist/agent-memory/index.cjs +1772 -0
  2. package/dist/agent-memory/index.d.ts +588 -0
  3. package/dist/agent-memory/index.mjs +1770 -0
  4. package/dist/agents/index.cjs +1995 -0
  5. package/dist/agents/index.d.ts +961 -0
  6. package/dist/agents/index.mjs +1993 -0
  7. package/dist/assets/index.cjs +171 -39
  8. package/dist/assets/index.d.ts +84 -5
  9. package/dist/assets/index.mjs +171 -39
  10. package/dist/attachments/index.cjs +53 -15
  11. package/dist/attachments/index.d.ts +1 -0
  12. package/dist/attachments/index.mjs +53 -15
  13. package/dist/buckets/index.cjs +151 -130
  14. package/dist/buckets/index.d.ts +198 -84
  15. package/dist/buckets/index.mjs +151 -130
  16. package/dist/cases/index.cjs +220 -23
  17. package/dist/cases/index.d.ts +148 -10
  18. package/dist/cases/index.mjs +220 -24
  19. package/dist/conversational-agent/index.cjs +140 -66
  20. package/dist/conversational-agent/index.d.ts +190 -122
  21. package/dist/conversational-agent/index.mjs +140 -66
  22. package/dist/core/index.cjs +445 -108
  23. package/dist/core/index.d.ts +15 -0
  24. package/dist/core/index.mjs +445 -108
  25. package/dist/entities/index.cjs +365 -102
  26. package/dist/entities/index.d.ts +446 -114
  27. package/dist/entities/index.mjs +365 -102
  28. package/dist/feedback/index.cjs +53 -15
  29. package/dist/feedback/index.d.ts +1 -0
  30. package/dist/feedback/index.mjs +53 -15
  31. package/dist/governance/index.cjs +1789 -0
  32. package/dist/governance/index.d.ts +598 -0
  33. package/dist/governance/index.mjs +1787 -0
  34. package/dist/index.cjs +1453 -444
  35. package/dist/index.d.ts +4150 -1742
  36. package/dist/index.mjs +1452 -445
  37. package/dist/index.umd.js +5035 -4009
  38. package/dist/jobs/index.cjs +53 -15
  39. package/dist/jobs/index.d.ts +1 -0
  40. package/dist/jobs/index.mjs +53 -15
  41. package/dist/maestro-processes/index.cjs +189 -27
  42. package/dist/maestro-processes/index.d.ts +131 -9
  43. package/dist/maestro-processes/index.mjs +189 -27
  44. package/dist/orchestrator-du-module/index.cjs +1788 -0
  45. package/dist/orchestrator-du-module/index.d.ts +757 -0
  46. package/dist/orchestrator-du-module/index.mjs +1785 -0
  47. package/dist/processes/index.cjs +53 -15
  48. package/dist/processes/index.d.ts +1 -0
  49. package/dist/processes/index.mjs +53 -15
  50. package/dist/queues/index.cjs +53 -15
  51. package/dist/queues/index.d.ts +1 -0
  52. package/dist/queues/index.mjs +53 -15
  53. package/dist/tasks/index.cjs +116 -19
  54. package/dist/tasks/index.d.ts +110 -4
  55. package/dist/tasks/index.mjs +117 -20
  56. package/dist/traces/index.cjs +340 -15
  57. package/dist/traces/index.d.ts +483 -2
  58. package/dist/traces/index.mjs +339 -16
  59. package/package.json +42 -2
@@ -0,0 +1,1787 @@
1
+ import { getOrCreateClient, createTrack, createTrackEvent } from '@uipath/core-telemetry';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+
20
+ function __decorate(decorators, target, key, desc) {
21
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
23
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+
27
+ function __classPrivateFieldGet(receiver, state, kind, f) {
28
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
29
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
30
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
31
+ }
32
+
33
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
34
+ if (kind === "m") throw new TypeError("Private method is not writable");
35
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
36
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
37
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
38
+ }
39
+
40
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
41
+ var e = new Error(message);
42
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
43
+ };
44
+
45
+ /**
46
+ * Type guards for error response types
47
+ */
48
+ function isOrchestratorError(error) {
49
+ return typeof error === 'object' &&
50
+ error !== null &&
51
+ 'message' in error &&
52
+ 'errorCode' in error &&
53
+ typeof error.message === 'string' &&
54
+ typeof error.errorCode === 'number';
55
+ }
56
+ function isEntityError(error) {
57
+ return typeof error === 'object' &&
58
+ error !== null &&
59
+ 'error' in error &&
60
+ typeof error.error === 'string';
61
+ }
62
+ function isPimsError(error) {
63
+ return typeof error === 'object' &&
64
+ error !== null &&
65
+ 'type' in error &&
66
+ 'title' in error &&
67
+ 'status' in error &&
68
+ typeof error.type === 'string' &&
69
+ typeof error.title === 'string' &&
70
+ typeof error.status === 'number';
71
+ }
72
+
73
+ /**
74
+ * HTTP status code constants for error handling
75
+ */
76
+ const HttpStatus = {
77
+ // Client errors (4xx)
78
+ BAD_REQUEST: 400,
79
+ UNAUTHORIZED: 401,
80
+ FORBIDDEN: 403,
81
+ NOT_FOUND: 404,
82
+ TOO_MANY_REQUESTS: 429,
83
+ // Server errors (5xx)
84
+ INTERNAL_SERVER_ERROR: 500,
85
+ BAD_GATEWAY: 502,
86
+ SERVICE_UNAVAILABLE: 503,
87
+ GATEWAY_TIMEOUT: 504
88
+ };
89
+ /**
90
+ * Error type constants for consistent error identification
91
+ */
92
+ const ErrorType = {
93
+ AUTHENTICATION: 'AuthenticationError',
94
+ AUTHORIZATION: 'AuthorizationError',
95
+ VALIDATION: 'ValidationError',
96
+ NOT_FOUND: 'NotFoundError',
97
+ RATE_LIMIT: 'RateLimitError',
98
+ SERVER: 'ServerError',
99
+ NETWORK: 'NetworkError'
100
+ };
101
+ /**
102
+ * HTTP header constants for error handling
103
+ */
104
+ const HttpHeaders = {
105
+ X_REQUEST_ID: 'x-request-id'
106
+ };
107
+ /**
108
+ * Standard error message constants
109
+ */
110
+ const ErrorMessages = {
111
+ // Authentication errors
112
+ AUTHENTICATION_FAILED: 'Authentication failed',
113
+ // Authorization errors
114
+ ACCESS_DENIED: 'Access denied',
115
+ // Validation errors
116
+ VALIDATION_FAILED: 'Validation failed',
117
+ // Not found errors
118
+ RESOURCE_NOT_FOUND: 'Resource not found',
119
+ // Rate limit errors
120
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
121
+ // Server errors
122
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
123
+ // Network errors
124
+ NETWORK_ERROR: 'Network error occurred',
125
+ REQUEST_TIMEOUT: 'Request timed out',
126
+ REQUEST_ABORTED: 'Request was aborted',
127
+ };
128
+ /**
129
+ * Error name constants for network error identification
130
+ */
131
+ const ErrorNames = {
132
+ ABORT_ERROR: 'AbortError'};
133
+
134
+ /**
135
+ * Parser for Orchestrator/Task error format
136
+ */
137
+ class OrchestratorErrorParser {
138
+ canParse(errorBody) {
139
+ return isOrchestratorError(errorBody);
140
+ }
141
+ parse(errorBody, response) {
142
+ const error = errorBody;
143
+ return {
144
+ message: error.message,
145
+ code: response?.status?.toString(),
146
+ details: {
147
+ errorCode: error.errorCode,
148
+ traceId: error.traceId,
149
+ originalResponse: error
150
+ },
151
+ requestId: error.traceId
152
+ };
153
+ }
154
+ }
155
+ /**
156
+ * Parser for Entity (Data Fabric) error format
157
+ */
158
+ class EntityErrorParser {
159
+ canParse(errorBody) {
160
+ return isEntityError(errorBody);
161
+ }
162
+ parse(errorBody, response) {
163
+ const error = errorBody;
164
+ return {
165
+ message: error.error,
166
+ code: response?.status?.toString(),
167
+ details: {
168
+ error: error.error,
169
+ traceId: error.traceId,
170
+ originalResponse: error
171
+ },
172
+ requestId: error.traceId
173
+ };
174
+ }
175
+ }
176
+ /**
177
+ * Parser for PIMS error format
178
+ */
179
+ class PimsErrorParser {
180
+ canParse(errorBody) {
181
+ return isPimsError(errorBody);
182
+ }
183
+ parse(errorBody, response) {
184
+ const error = errorBody;
185
+ let message = error.title;
186
+ // If there are validation errors, append them to the message for better visibility
187
+ if (error.errors && Object.keys(error.errors).length > 0) {
188
+ const errorMessages = Object.entries(error.errors)
189
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
190
+ .join('; ');
191
+ message += `. Validation errors: ${errorMessages}`;
192
+ }
193
+ return {
194
+ message,
195
+ code: response?.status?.toString(),
196
+ details: {
197
+ type: error.type,
198
+ title: error.title,
199
+ status: error.status,
200
+ errors: error.errors,
201
+ traceId: error.traceId,
202
+ originalResponse: error
203
+ },
204
+ requestId: error.traceId
205
+ };
206
+ }
207
+ }
208
+ /**
209
+ * Fallback parser for unrecognized formats
210
+ */
211
+ class GenericErrorParser {
212
+ canParse(_errorBody) {
213
+ return true; // Always can parse as last resort
214
+ }
215
+ parse(errorBody, response) {
216
+ // For unknown error formats, just pass through the raw error with fallback message
217
+ const message = response?.statusText || 'An error occurred';
218
+ return {
219
+ message,
220
+ code: response?.status?.toString(),
221
+ details: {
222
+ originalResponse: errorBody
223
+ },
224
+ };
225
+ }
226
+ }
227
+ /**
228
+ * Main error response parser using Chain of Responsibility pattern
229
+ *
230
+ * This parser standardizes error responses from different UiPath services into a
231
+ * consistent format, regardless of the original error structure.
232
+ *
233
+ * Supported formats:
234
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
235
+ * 2. Entity (Data Fabric): { error, traceId }
236
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
237
+ * 4. Generic: Fallback for any other format
238
+ *
239
+ * @example
240
+ * const parser = new ErrorResponseParser();
241
+ * const errorInfo = await parser.parse(response);
242
+ * // errorInfo will have consistent structure regardless of service
243
+ */
244
+ class ErrorResponseParser {
245
+ constructor() {
246
+ this.strategies = [
247
+ new OrchestratorErrorParser(),
248
+ new EntityErrorParser(),
249
+ new PimsErrorParser(),
250
+ new GenericErrorParser() // Must be last
251
+ ];
252
+ }
253
+ /**
254
+ * Parses error response body into standardized format
255
+ * @param response - The HTTP response object
256
+ * @returns Standardized error information
257
+ */
258
+ async parse(response) {
259
+ try {
260
+ const errorBody = await response.json();
261
+ // Find the first strategy that can parse this error format
262
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
263
+ // GenericErrorParser always returns true, so this will never be null
264
+ return strategy.parse(errorBody, response);
265
+ }
266
+ catch {
267
+ // Handle non-JSON responses
268
+ const responseText = await response.text().catch(() => '');
269
+ return {
270
+ message: response.statusText,
271
+ code: response.status.toString(),
272
+ details: {
273
+ parseError: 'Failed to parse error response as JSON',
274
+ responseText
275
+ },
276
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
277
+ };
278
+ }
279
+ }
280
+ }
281
+ // Export singleton instance
282
+ const errorResponseParser = new ErrorResponseParser();
283
+
284
+ /**
285
+ * Base error class for all UiPath SDK errors
286
+ * Extends Error for standard error handling compatibility
287
+ */
288
+ class UiPathError extends Error {
289
+ constructor(type, params) {
290
+ super(params.message);
291
+ this.name = type;
292
+ this.type = type;
293
+ this.statusCode = params.statusCode;
294
+ this.requestId = params.requestId;
295
+ this.timestamp = new Date();
296
+ // Maintains proper stack trace for where our error was thrown
297
+ if (Error.captureStackTrace) {
298
+ Error.captureStackTrace(this, this.constructor);
299
+ }
300
+ }
301
+ /**
302
+ * Returns a clean JSON representation of the error
303
+ */
304
+ toJSON() {
305
+ return {
306
+ type: this.type,
307
+ message: this.message,
308
+ statusCode: this.statusCode,
309
+ requestId: this.requestId,
310
+ timestamp: this.timestamp
311
+ };
312
+ }
313
+ /**
314
+ * Returns detailed debug information including stack trace
315
+ */
316
+ getDebugInfo() {
317
+ return {
318
+ ...this.toJSON(),
319
+ stack: this.stack
320
+ };
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Error thrown when authentication fails (401 errors)
326
+ * Common scenarios:
327
+ * - Invalid credentials
328
+ * - Expired token
329
+ * - Missing authentication
330
+ */
331
+ class AuthenticationError extends UiPathError {
332
+ constructor(params = {}) {
333
+ super(ErrorType.AUTHENTICATION, {
334
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
335
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
336
+ requestId: params.requestId
337
+ });
338
+ }
339
+ }
340
+
341
+ /**
342
+ * Error thrown when authorization fails (403 errors)
343
+ * Common scenarios:
344
+ * - Insufficient permissions
345
+ * - Access denied to resource
346
+ * - Invalid scope
347
+ */
348
+ class AuthorizationError extends UiPathError {
349
+ constructor(params = {}) {
350
+ super(ErrorType.AUTHORIZATION, {
351
+ message: params.message || ErrorMessages.ACCESS_DENIED,
352
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
353
+ requestId: params.requestId
354
+ });
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Error thrown when validation fails (400 errors or client-side validation)
360
+ * Common scenarios:
361
+ * - Invalid input parameters
362
+ * - Missing required fields
363
+ * - Invalid data format
364
+ */
365
+ class ValidationError extends UiPathError {
366
+ constructor(params = {}) {
367
+ super(ErrorType.VALIDATION, {
368
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
369
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
370
+ requestId: params.requestId
371
+ });
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Error thrown when a resource is not found (404 errors)
377
+ * Common scenarios:
378
+ * - Resource doesn't exist
379
+ * - Invalid ID provided
380
+ * - Resource deleted
381
+ */
382
+ class NotFoundError extends UiPathError {
383
+ constructor(params = {}) {
384
+ super(ErrorType.NOT_FOUND, {
385
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
386
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
387
+ requestId: params.requestId
388
+ });
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Error thrown when rate limit is exceeded (429 errors)
394
+ * Common scenarios:
395
+ * - Too many requests in a time window
396
+ * - API throttling
397
+ */
398
+ class RateLimitError extends UiPathError {
399
+ constructor(params = {}) {
400
+ super(ErrorType.RATE_LIMIT, {
401
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
402
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
403
+ requestId: params.requestId
404
+ });
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Error thrown when server encounters an error (5xx errors)
410
+ * Common scenarios:
411
+ * - Internal server error
412
+ * - Service unavailable
413
+ * - Gateway timeout
414
+ */
415
+ class ServerError extends UiPathError {
416
+ constructor(params = {}) {
417
+ super(ErrorType.SERVER, {
418
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
419
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
420
+ requestId: params.requestId
421
+ });
422
+ }
423
+ /**
424
+ * Checks if this is a temporary error that might succeed on retry
425
+ */
426
+ get isRetryable() {
427
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
428
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
429
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Error thrown when network/connection issues occur
435
+ * Common scenarios:
436
+ * - Connection timeout
437
+ * - DNS resolution failure
438
+ * - Network unreachable
439
+ * - Request aborted
440
+ */
441
+ class NetworkError extends UiPathError {
442
+ constructor(params = {}) {
443
+ super(ErrorType.NETWORK, {
444
+ message: params.message || ErrorMessages.NETWORK_ERROR,
445
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
446
+ requestId: params.requestId
447
+ });
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Factory for creating typed errors based on HTTP status codes
453
+ * Follows the Factory pattern for clean error instantiation
454
+ */
455
+ class ErrorFactory {
456
+ /**
457
+ * Creates appropriate error instance based on HTTP status code
458
+ */
459
+ static createFromHttpStatus(statusCode, errorInfo) {
460
+ const { message, requestId } = errorInfo;
461
+ // Map status codes to error types
462
+ switch (statusCode) {
463
+ case HttpStatus.BAD_REQUEST:
464
+ return new ValidationError({ message, statusCode, requestId });
465
+ case HttpStatus.UNAUTHORIZED:
466
+ return new AuthenticationError({ message, statusCode, requestId });
467
+ case HttpStatus.FORBIDDEN:
468
+ return new AuthorizationError({ message, statusCode, requestId });
469
+ case HttpStatus.NOT_FOUND:
470
+ return new NotFoundError({ message, statusCode, requestId });
471
+ case HttpStatus.TOO_MANY_REQUESTS:
472
+ return new RateLimitError({ message, statusCode, requestId });
473
+ default:
474
+ // For 5xx errors or any other status code
475
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
476
+ return new ServerError({ message, statusCode, requestId });
477
+ }
478
+ // For unknown client errors, treat as validation error
479
+ return new ValidationError({
480
+ message: `${message} (HTTP ${statusCode})`,
481
+ statusCode,
482
+ requestId
483
+ });
484
+ }
485
+ }
486
+ /**
487
+ * Creates a NetworkError from a fetch/network error
488
+ */
489
+ static createNetworkError(error) {
490
+ let message = ErrorMessages.NETWORK_ERROR;
491
+ if (error instanceof Error) {
492
+ if (error.name === ErrorNames.ABORT_ERROR) {
493
+ message = ErrorMessages.REQUEST_ABORTED;
494
+ }
495
+ else if (error.message.includes('timeout')) {
496
+ message = ErrorMessages.REQUEST_TIMEOUT;
497
+ }
498
+ else {
499
+ message = error.message;
500
+ }
501
+ }
502
+ return new NetworkError({ message });
503
+ }
504
+ }
505
+
506
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
507
+ const TRACEPARENT = 'traceparent';
508
+ const UIPATH_TRACEPARENT_ID = 'x-uipath-traceparent-id';
509
+ /**
510
+ * Content type constants for HTTP requests/responses
511
+ */
512
+ const CONTENT_TYPES = {
513
+ JSON: 'application/json',
514
+ XML: 'application/xml',
515
+ OCTET_STREAM: 'application/octet-stream'
516
+ };
517
+ /**
518
+ * Response type constants for HTTP requests
519
+ */
520
+ const RESPONSE_TYPES = {
521
+ JSON: 'json',
522
+ TEXT: 'text',
523
+ BLOB: 'blob',
524
+ ARRAYBUFFER: 'arraybuffer'
525
+ };
526
+
527
+ class ApiClient {
528
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
529
+ this.config = config;
530
+ this.executionContext = executionContext;
531
+ this.clientConfig = clientConfig;
532
+ this.tokenManager = tokenManager;
533
+ }
534
+ /**
535
+ * Gets a valid authentication token, refreshing if necessary.
536
+ * Used internally for API requests and exposed for services that need manual auth headers.
537
+ *
538
+ * @returns The valid token
539
+ * @throws AuthenticationError if no token available or refresh fails
540
+ */
541
+ async getValidToken() {
542
+ return this.tokenManager.getValidToken();
543
+ }
544
+ async getDefaultHeaders() {
545
+ const token = await this.getValidToken();
546
+ return {
547
+ 'Authorization': `Bearer ${token}`,
548
+ 'Content-Type': CONTENT_TYPES.JSON,
549
+ ...this.clientConfig.headers
550
+ };
551
+ }
552
+ async request(method, path, options = {}) {
553
+ // Ensure path starts with a forward slash
554
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
555
+ // Construct URL with org and tenant names
556
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
557
+ const isFormData = options.body instanceof FormData;
558
+ const defaultHeaders = await this.getDefaultHeaders();
559
+ if (isFormData) {
560
+ delete defaultHeaders['Content-Type'];
561
+ }
562
+ const traceId = crypto.randomUUID().replace(/-/g, '');
563
+ const spanId = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
564
+ const traceparentValue = `00-${traceId}-${spanId}-01`;
565
+ const headers = {
566
+ ...defaultHeaders,
567
+ [TRACEPARENT]: traceparentValue,
568
+ [UIPATH_TRACEPARENT_ID]: traceparentValue,
569
+ ...options.headers
570
+ };
571
+ // Convert params to URLSearchParams
572
+ const searchParams = new URLSearchParams();
573
+ if (options.params) {
574
+ Object.entries(options.params).forEach(([key, value]) => {
575
+ searchParams.append(key, value.toString());
576
+ });
577
+ }
578
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
579
+ let body = undefined;
580
+ if (options.body) {
581
+ body = isFormData ? options.body : JSON.stringify(options.body);
582
+ }
583
+ try {
584
+ const response = await fetch(fullUrl, {
585
+ method,
586
+ headers,
587
+ body,
588
+ signal: options.signal
589
+ });
590
+ if (!response.ok) {
591
+ const errorInfo = await errorResponseParser.parse(response);
592
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
593
+ }
594
+ if (response.status === 204) {
595
+ return undefined;
596
+ }
597
+ // Handle blob response type for binary data (e.g., file downloads)
598
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
599
+ const blob = await response.blob();
600
+ return blob;
601
+ }
602
+ // Check if we're expecting XML
603
+ const acceptHeader = headers['Accept'] || headers['accept'];
604
+ if (acceptHeader === CONTENT_TYPES.XML) {
605
+ const text = await response.text();
606
+ return text;
607
+ }
608
+ const text = await response.text();
609
+ if (!text) {
610
+ return undefined;
611
+ }
612
+ try {
613
+ return JSON.parse(text);
614
+ }
615
+ catch (error) {
616
+ if (error instanceof SyntaxError) {
617
+ throw new ServerError({
618
+ message: `Server returned non-JSON response (${response.status} ${response.url}): ${error.message}`,
619
+ statusCode: response.status,
620
+ });
621
+ }
622
+ throw error;
623
+ }
624
+ }
625
+ catch (error) {
626
+ // If it's already one of our errors, re-throw it
627
+ if (error.type && error.type.includes('Error')) {
628
+ throw error;
629
+ }
630
+ // Otherwise, it's a genuine network/fetch failure
631
+ throw ErrorFactory.createNetworkError(error);
632
+ }
633
+ }
634
+ async get(path, options = {}) {
635
+ return this.request('GET', path, options);
636
+ }
637
+ async post(path, data, options = {}) {
638
+ return this.request('POST', path, { ...options, body: data });
639
+ }
640
+ async put(path, data, options = {}) {
641
+ return this.request('PUT', path, { ...options, body: data });
642
+ }
643
+ async patch(path, data, options = {}) {
644
+ return this.request('PATCH', path, { ...options, body: data });
645
+ }
646
+ async delete(path, options = {}) {
647
+ return this.request('DELETE', path, options);
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Pagination types supported by the SDK
653
+ */
654
+ var PaginationType;
655
+ (function (PaginationType) {
656
+ PaginationType["OFFSET"] = "offset";
657
+ PaginationType["TOKEN"] = "token";
658
+ })(PaginationType || (PaginationType = {}));
659
+
660
+ /**
661
+ * Collection of utility functions for working with objects
662
+ */
663
+ /**
664
+ * Resolves a field value from an object, supporting both direct keys (e.g., '@odata.count')
665
+ * and dot-separated nested paths (e.g., 'pagination.totalCount').
666
+ * Direct key match takes priority over nested traversal.
667
+ */
668
+ function resolveNestedField(data, fieldPath) {
669
+ if (!data) {
670
+ return undefined;
671
+ }
672
+ if (fieldPath in data) {
673
+ return data[fieldPath];
674
+ }
675
+ if (!fieldPath.includes('.')) {
676
+ return undefined;
677
+ }
678
+ let value = data;
679
+ for (const part of fieldPath.split('.')) {
680
+ value = value?.[part];
681
+ }
682
+ return value;
683
+ }
684
+ /**
685
+ * Filters out undefined values from an object
686
+ * @param obj The source object
687
+ * @returns A new object without undefined values
688
+ *
689
+ * @example
690
+ * ```typescript
691
+ * // Object with undefined values
692
+ * const options = {
693
+ * name: 'test',
694
+ * count: 5,
695
+ * prefix: undefined,
696
+ * suffix: null
697
+ * };
698
+ * const result = filterUndefined(options);
699
+ * // result = { name: 'test', count: 5, suffix: null }
700
+ * ```
701
+ */
702
+ function filterUndefined(obj) {
703
+ const result = {};
704
+ for (const [key, value] of Object.entries(obj)) {
705
+ if (value !== undefined) {
706
+ result[key] = value;
707
+ }
708
+ }
709
+ return result;
710
+ }
711
+
712
+ /**
713
+ * Utility functions for platform detection
714
+ */
715
+ /**
716
+ * Checks if code is running in a browser environment
717
+ */
718
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
719
+ isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
720
+ const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
721
+ /**
722
+ * True when the coded app has been loaded inside a host frame that explicitly
723
+ * opted into token delegation by adding `?host=embed` to the iframe src URL.
724
+ */
725
+ const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
726
+ /**
727
+ * The validated parent origin, read from the `?basedomain=` query param set
728
+ * by the embedding host in the iframe src URL.
729
+ * Mirrors the same mechanism used by ActionCenterTokenManager.
730
+ * Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
731
+ */
732
+ (() => {
733
+ if (!isHostEmbedded)
734
+ return null;
735
+ const basedomain = _params?.get('basedomain');
736
+ if (!basedomain)
737
+ return null;
738
+ try {
739
+ return new URL(basedomain).origin;
740
+ }
741
+ catch {
742
+ console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
743
+ return null;
744
+ }
745
+ })();
746
+
747
+ /**
748
+ * Base64 encoding/decoding
749
+ */
750
+ /**
751
+ * Encodes a string to base64
752
+ * @param str - The string to encode
753
+ * @returns Base64 encoded string
754
+ */
755
+ function encodeBase64(str) {
756
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
757
+ const encoder = new TextEncoder();
758
+ const data = encoder.encode(str);
759
+ // Convert Uint8Array to base64
760
+ if (isBrowser) {
761
+ // Browser environment
762
+ // Convert Uint8Array to binary string then to base64
763
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
764
+ return btoa(binaryString);
765
+ }
766
+ else {
767
+ // Node.js environment
768
+ return Buffer.from(data).toString('base64');
769
+ }
770
+ }
771
+ /**
772
+ * Decodes a base64 string
773
+ * @param base64 - The base64 string to decode
774
+ * @returns Decoded string
775
+ */
776
+ function decodeBase64(base64) {
777
+ let bytes;
778
+ if (isBrowser) {
779
+ // Browser environment
780
+ const binaryString = atob(base64);
781
+ bytes = new Uint8Array(binaryString.length);
782
+ for (let i = 0; i < binaryString.length; i++) {
783
+ bytes[i] = binaryString.charCodeAt(i);
784
+ }
785
+ }
786
+ else {
787
+ // Node.js environment
788
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
789
+ }
790
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
791
+ const decoder = new TextDecoder();
792
+ return decoder.decode(bytes);
793
+ }
794
+
795
+ /**
796
+ * PaginationManager handles the conversion between uniform cursor-based pagination
797
+ * and the specific pagination type for each service
798
+ */
799
+ class PaginationManager {
800
+ /**
801
+ * Create a pagination cursor for subsequent page requests
802
+ */
803
+ static createCursor({ pageInfo, type }) {
804
+ if (!pageInfo.hasMore) {
805
+ return undefined;
806
+ }
807
+ const cursorData = {
808
+ type,
809
+ pageSize: pageInfo.pageSize,
810
+ };
811
+ switch (type) {
812
+ case PaginationType.OFFSET:
813
+ if (pageInfo.currentPage) {
814
+ cursorData.pageNumber = pageInfo.currentPage + 1;
815
+ }
816
+ break;
817
+ case PaginationType.TOKEN:
818
+ if (pageInfo.continuationToken) {
819
+ cursorData.continuationToken = pageInfo.continuationToken;
820
+ }
821
+ else {
822
+ return undefined; // No continuation token, can't continue
823
+ }
824
+ break;
825
+ }
826
+ return {
827
+ value: encodeBase64(JSON.stringify(cursorData))
828
+ };
829
+ }
830
+ /**
831
+ * Create a paginated response with navigation cursors
832
+ */
833
+ static createPaginatedResponse({ pageInfo, type }, items) {
834
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
835
+ // Create previous page cursor if applicable
836
+ let previousCursor = undefined;
837
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
838
+ const prevCursorData = {
839
+ type,
840
+ pageNumber: pageInfo.currentPage - 1,
841
+ pageSize: pageInfo.pageSize,
842
+ };
843
+ previousCursor = {
844
+ value: encodeBase64(JSON.stringify(prevCursorData))
845
+ };
846
+ }
847
+ // Calculate total pages if we have totalCount and pageSize
848
+ let totalPages = undefined;
849
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
850
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
851
+ }
852
+ // Determine if this pagination type supports page jumping
853
+ const supportsPageJump = type === PaginationType.OFFSET;
854
+ // Create the result object with all fields, then filter out undefined values
855
+ const result = filterUndefined({
856
+ items,
857
+ totalCount: pageInfo.totalCount,
858
+ hasNextPage: pageInfo.hasMore,
859
+ nextCursor: nextCursor,
860
+ previousCursor: previousCursor,
861
+ currentPage: pageInfo.currentPage,
862
+ totalPages,
863
+ supportsPageJump
864
+ });
865
+ return result;
866
+ }
867
+ }
868
+
869
+ /**
870
+ * Creates headers object from key-value pairs
871
+ * @param headersObj - Object containing header key-value pairs
872
+ * @returns Headers object with all values converted to strings
873
+ *
874
+ * @example
875
+ * ```typescript
876
+ * // Single header
877
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
878
+ *
879
+ * // Multiple headers
880
+ * const headers = createHeaders({
881
+ * 'X-UIPATH-FolderKey': '1234567890',
882
+ * 'X-UIPATH-OrganizationUnitId': 123,
883
+ * 'Accept': 'application/json'
884
+ * });
885
+ *
886
+ * // Using constants
887
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
888
+ * const headers = createHeaders({
889
+ * [FOLDER_KEY]: 'abc-123',
890
+ * [FOLDER_ID]: 456
891
+ * });
892
+ *
893
+ * // Empty headers
894
+ * const headers = createHeaders();
895
+ * ```
896
+ */
897
+ function createHeaders(headersObj) {
898
+ const headers = {};
899
+ for (const [key, value] of Object.entries(headersObj)) {
900
+ if (value !== undefined && value !== null) {
901
+ headers[key] = value.toString();
902
+ }
903
+ }
904
+ return headers;
905
+ }
906
+
907
+ /**
908
+ * Common constants used across the SDK
909
+ */
910
+ /**
911
+ * Prefix used for OData query parameters
912
+ */
913
+ const ODATA_PREFIX = '$';
914
+ /**
915
+ * HTTP methods
916
+ */
917
+ const HTTP_METHODS = {
918
+ GET: 'GET',
919
+ POST: 'POST'};
920
+ /**
921
+ * Governance pagination constants for page-number-based pagination
922
+ */
923
+ const GOVERNANCE_PAGINATION = {
924
+ /** Field name for items in governance response */
925
+ ITEMS_FIELD: 'items'
926
+ };
927
+ /**
928
+ * Governance OFFSET pagination parameter names (page-number style, 0-based, no skip conversion)
929
+ */
930
+ const GOVERNANCE_OFFSET_PARAMS = {
931
+ /** Page size parameter name */
932
+ PAGE_SIZE_PARAM: 'pageSize',
933
+ /** Page number parameter name (sent directly, 0-based) */
934
+ OFFSET_PARAM: 'pageNumber',
935
+ /** No count param needed */
936
+ COUNT_PARAM: undefined
937
+ };
938
+ /**
939
+ * OData OFFSET pagination parameter names (ODATA-style)
940
+ */
941
+ const ODATA_OFFSET_PARAMS = {
942
+ /** OData page size parameter name */
943
+ PAGE_SIZE_PARAM: '$top',
944
+ /** OData offset parameter name */
945
+ OFFSET_PARAM: '$skip',
946
+ /** OData count parameter name */
947
+ COUNT_PARAM: '$count'
948
+ };
949
+ /**
950
+ * Bucket TOKEN pagination parameter names
951
+ */
952
+ const BUCKET_TOKEN_PARAMS = {
953
+ /** Bucket page size parameter name */
954
+ PAGE_SIZE_PARAM: 'takeHint',
955
+ /** Bucket token parameter name */
956
+ TOKEN_PARAM: 'continuationToken'
957
+ };
958
+
959
+ /**
960
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
961
+ * Returns the original value if parsing fails.
962
+ */
963
+ /**
964
+ * Adds a prefix to specified keys in an object, returning a new object.
965
+ * Only the provided keys are prefixed; all others are left unchanged.
966
+ *
967
+ * @param obj The source object
968
+ * @param prefix The prefix to add (e.g., '$')
969
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
970
+ * @returns A new object with specified keys prefixed
971
+ *
972
+ * @example
973
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
974
+ */
975
+ function addPrefixToKeys(obj, prefix, keys) {
976
+ const result = {};
977
+ for (const [key, value] of Object.entries(obj)) {
978
+ if (keys.includes(key)) {
979
+ result[`${prefix}${key}`] = value;
980
+ }
981
+ else {
982
+ result[key] = value;
983
+ }
984
+ }
985
+ return result;
986
+ }
987
+
988
+ /**
989
+ * Constants used throughout the pagination system
990
+ */
991
+ /** Maximum number of items that can be requested in a single page */
992
+ const MAX_PAGE_SIZE = 1000;
993
+ /** Default page size when jumpToPage is used without specifying pageSize */
994
+ const DEFAULT_PAGE_SIZE = 50;
995
+ /** Default field name for items in a paginated response */
996
+ const DEFAULT_ITEMS_FIELD = 'value';
997
+ /** Default field name for total count in a paginated response */
998
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
999
+ /**
1000
+ * Limits the page size to the maximum allowed value
1001
+ * @param pageSize - Requested page size
1002
+ * @returns Limited page size value
1003
+ */
1004
+ function getLimitedPageSize(pageSize) {
1005
+ if (pageSize === undefined || pageSize === null) {
1006
+ return DEFAULT_PAGE_SIZE;
1007
+ }
1008
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1009
+ }
1010
+
1011
+ /**
1012
+ * Helper functions for pagination that can be used across services
1013
+ */
1014
+ class PaginationHelpers {
1015
+ /**
1016
+ * Checks if any pagination parameters are provided
1017
+ *
1018
+ * @param options - The options object to check
1019
+ * @returns True if any pagination parameter is defined, false otherwise
1020
+ */
1021
+ static hasPaginationParameters(options = {}) {
1022
+ const { cursor, pageSize, jumpToPage } = options;
1023
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1024
+ }
1025
+ /**
1026
+ * Parse a pagination cursor string into cursor data
1027
+ */
1028
+ static parseCursor(cursorString) {
1029
+ try {
1030
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1031
+ return cursorData;
1032
+ }
1033
+ catch {
1034
+ throw new Error('Invalid pagination cursor');
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Validates cursor format and structure
1039
+ *
1040
+ * @param paginationOptions - The pagination options containing the cursor
1041
+ * @param paginationType - Optional pagination type to validate against
1042
+ */
1043
+ static validateCursor(paginationOptions, paginationType) {
1044
+ if (paginationOptions.cursor !== undefined) {
1045
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1046
+ throw new Error('cursor must contain a valid cursor string');
1047
+ }
1048
+ try {
1049
+ // Try to parse the cursor to validate it
1050
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1051
+ // If type is provided, validate cursor contains expected type information
1052
+ if (paginationType) {
1053
+ if (!cursorData.type) {
1054
+ throw new Error('Invalid cursor: missing pagination type');
1055
+ }
1056
+ // Check pagination type compatibility
1057
+ if (cursorData.type !== paginationType) {
1058
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1059
+ }
1060
+ }
1061
+ }
1062
+ catch (error) {
1063
+ if (error instanceof Error) {
1064
+ // If it's already our error with specific message, pass it through
1065
+ if (error.message.startsWith('Invalid cursor') ||
1066
+ error.message.startsWith('Pagination type mismatch')) {
1067
+ throw error;
1068
+ }
1069
+ }
1070
+ throw new Error('Invalid pagination cursor format');
1071
+ }
1072
+ }
1073
+ }
1074
+ /**
1075
+ * Comprehensive validation for pagination options
1076
+ *
1077
+ * @param options - The pagination options to validate
1078
+ * @param paginationType - The pagination type these options will be used with
1079
+ * @returns Processed pagination parameters ready for use
1080
+ */
1081
+ static validatePaginationOptions(options, paginationType) {
1082
+ // Validate pageSize
1083
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1084
+ throw new Error('pageSize must be a positive number');
1085
+ }
1086
+ // Validate jumpToPage
1087
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1088
+ throw new Error('jumpToPage must be a positive number');
1089
+ }
1090
+ // Validate cursor
1091
+ PaginationHelpers.validateCursor(options, paginationType);
1092
+ // Validate service compatibility
1093
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1094
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1095
+ }
1096
+ // Get processed parameters
1097
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1098
+ }
1099
+ /**
1100
+ * Convert a unified pagination options to service-specific parameters
1101
+ */
1102
+ static getRequestParameters(options, paginationType) {
1103
+ // Handle jumpToPage
1104
+ if (options.jumpToPage !== undefined) {
1105
+ const jumpToPageOptions = {
1106
+ pageSize: options.pageSize,
1107
+ pageNumber: options.jumpToPage
1108
+ };
1109
+ return filterUndefined(jumpToPageOptions);
1110
+ }
1111
+ // If no cursor is provided, it's a first page request
1112
+ if (!options.cursor) {
1113
+ const firstPageOptions = {
1114
+ pageSize: options.pageSize,
1115
+ // Only set pageNumber for OFFSET pagination
1116
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1117
+ };
1118
+ return filterUndefined(firstPageOptions);
1119
+ }
1120
+ // Parse the cursor
1121
+ try {
1122
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1123
+ const cursorBasedOptions = {
1124
+ pageSize: cursorData.pageSize || options.pageSize,
1125
+ pageNumber: cursorData.pageNumber,
1126
+ continuationToken: cursorData.continuationToken,
1127
+ type: cursorData.type,
1128
+ };
1129
+ return filterUndefined(cursorBasedOptions);
1130
+ }
1131
+ catch {
1132
+ throw new Error('Invalid pagination cursor');
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Helper method for paginated resource retrieval
1137
+ *
1138
+ * @param params - Parameters for pagination
1139
+ * @returns Promise resolving to a paginated result
1140
+ */
1141
+ static async getAllPaginated(params) {
1142
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1143
+ const endpoint = getEndpoint(folderId);
1144
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1145
+ // On POST, the caller's options go in the body; queryParams stays in the URL.
1146
+ // On GET, everything is URL — queryParams merges with additionalParams.
1147
+ const isPost = method === HTTP_METHODS.POST;
1148
+ const requestSpec = isPost
1149
+ ? { body: additionalParams, params: queryParams }
1150
+ : { params: { ...additionalParams, ...queryParams } };
1151
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1152
+ headers,
1153
+ ...requestSpec,
1154
+ pagination: {
1155
+ paginationType: options.paginationType || PaginationType.OFFSET,
1156
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1157
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1158
+ continuationTokenField: options.continuationTokenField,
1159
+ paginationParams: options.paginationParams
1160
+ }
1161
+ });
1162
+ // Parse items - automatically handle JSON string responses
1163
+ const rawItems = paginatedResponse.items;
1164
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1165
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1166
+ return {
1167
+ ...paginatedResponse,
1168
+ items: transformedItems
1169
+ };
1170
+ }
1171
+ /**
1172
+ * Helper method for non-paginated resource retrieval
1173
+ *
1174
+ * @param params - Parameters for non-paginated resource retrieval
1175
+ * @returns Promise resolving to an object with data and totalCount
1176
+ */
1177
+ static async getAllNonPaginated(params) {
1178
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, queryParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1179
+ // Set default field names
1180
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1181
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1182
+ // Determine endpoint and headers based on folderId
1183
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1184
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1185
+ // Make the API call based on method
1186
+ let response;
1187
+ if (method === HTTP_METHODS.POST) {
1188
+ response = await serviceAccess.post(endpoint, additionalParams, { headers, params: queryParams });
1189
+ }
1190
+ else {
1191
+ response = await serviceAccess.get(endpoint, {
1192
+ params: { ...additionalParams, ...queryParams },
1193
+ headers
1194
+ });
1195
+ }
1196
+ // Extract and transform items from response
1197
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1198
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1199
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1200
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1201
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1202
+ // Parse items - automatically handle JSON string responses
1203
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1204
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1205
+ return {
1206
+ items,
1207
+ totalCount
1208
+ };
1209
+ }
1210
+ /**
1211
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1212
+ *
1213
+ * @param config - Configuration for the getAll operation
1214
+ * @param options - Request options including pagination parameters
1215
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1216
+ */
1217
+ static async getAll(config, options) {
1218
+ const optionsWithDefaults = options || {};
1219
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1220
+ // Determine if pagination is requested
1221
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1222
+ // Process parameters (custom processing if provided, otherwise default)
1223
+ let processedOptions = restOptions;
1224
+ if (config.processParametersFn) {
1225
+ processedOptions = config.processParametersFn(restOptions, folderId);
1226
+ }
1227
+ // Apply ODATA prefix to keys (excluding specified keys)
1228
+ const excludeKeys = config.excludeFromPrefix || [];
1229
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1230
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1231
+ // Default pagination options
1232
+ const paginationOptions = {
1233
+ paginationType: PaginationType.OFFSET,
1234
+ itemsField: DEFAULT_ITEMS_FIELD,
1235
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1236
+ ...config.pagination
1237
+ };
1238
+ // Paginated flow
1239
+ if (isPaginationRequested) {
1240
+ return PaginationHelpers.getAllPaginated({
1241
+ serviceAccess: config.serviceAccess,
1242
+ getEndpoint: config.getEndpoint,
1243
+ folderId,
1244
+ headers: config.headers,
1245
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1246
+ additionalParams: prefixedOptions,
1247
+ queryParams: config.queryParams,
1248
+ transformFn: config.transformFn,
1249
+ method: config.method,
1250
+ options: {
1251
+ ...paginationOptions,
1252
+ paginationParams: config.pagination?.paginationParams
1253
+ }
1254
+ }); // Type assertion needed due to conditional return
1255
+ }
1256
+ // Non-paginated flow
1257
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1258
+ return PaginationHelpers.getAllNonPaginated({
1259
+ serviceAccess: config.serviceAccess,
1260
+ getAllEndpoint: config.getEndpoint(),
1261
+ getByFolderEndpoint: byFolderEndpoint,
1262
+ folderId,
1263
+ headers: config.headers,
1264
+ additionalParams: prefixedOptions,
1265
+ queryParams: config.queryParams,
1266
+ transformFn: config.transformFn,
1267
+ method: config.method,
1268
+ options: {
1269
+ itemsField: paginationOptions.itemsField,
1270
+ totalCountField: paginationOptions.totalCountField
1271
+ }
1272
+ });
1273
+ }
1274
+ }
1275
+
1276
+ /**
1277
+ * SDK Internals Registry - Internal registry for SDK instances
1278
+ *
1279
+ * This class is NOT exported in the public API.
1280
+ * It provides a secure way to share SDK internals between
1281
+ * the UiPath class and service classes without exposing them publicly.
1282
+ *
1283
+ * @internal
1284
+ */
1285
+ // Global symbol key to ensure WeakMap is shared across module instances
1286
+ // This prevents issues when core and service modules are bundled separately
1287
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1288
+ // Get or create the global WeakMap store
1289
+ const getGlobalStore = () => {
1290
+ const globalObj = globalThis;
1291
+ if (!globalObj[REGISTRY_KEY]) {
1292
+ globalObj[REGISTRY_KEY] = new WeakMap();
1293
+ }
1294
+ return globalObj[REGISTRY_KEY];
1295
+ };
1296
+ /**
1297
+ * Internal registry for SDK private components.
1298
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1299
+ * garbage collected when the SDK instance is no longer referenced.
1300
+ *
1301
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1302
+ * across separately bundled modules (core, entities, tasks, etc.).
1303
+ *
1304
+ * @internal - Not exported in public API
1305
+ */
1306
+ class SDKInternalsRegistry {
1307
+ // Use global store to ensure sharing across module bundles
1308
+ static get store() {
1309
+ return getGlobalStore();
1310
+ }
1311
+ /**
1312
+ * Register SDK instance internals
1313
+ * Called by UiPath constructor
1314
+ */
1315
+ static set(instance, internals) {
1316
+ this.store.set(instance, internals);
1317
+ }
1318
+ /**
1319
+ * Retrieve SDK instance internals
1320
+ * Called by BaseService constructor
1321
+ */
1322
+ static get(instance) {
1323
+ const internals = this.store.get(instance);
1324
+ if (!internals) {
1325
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1326
+ }
1327
+ return internals;
1328
+ }
1329
+ }
1330
+
1331
+ var _BaseService_apiClient;
1332
+ /**
1333
+ * Base class for all UiPath SDK services.
1334
+ *
1335
+ * Provides common functionality for authentication, configuration, and API communication.
1336
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1337
+ *
1338
+ * This class implements the dependency injection pattern where services receive a configured
1339
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1340
+ * including authentication token management.
1341
+ *
1342
+ * @remarks
1343
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1344
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1345
+ *
1346
+ */
1347
+ class BaseService {
1348
+ /**
1349
+ * Creates a base service instance with dependency injection.
1350
+ *
1351
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1352
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1353
+ * and token management internally.
1354
+ *
1355
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1356
+ * Services receive this via dependency injection in the modular pattern.
1357
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1358
+ * CAS external-app auth)
1359
+ *
1360
+ * @example
1361
+ * ```typescript
1362
+ * // Services automatically call this via super()
1363
+ * export class EntityService extends BaseService {
1364
+ * constructor(instance: IUiPath) {
1365
+ * super(instance); // Initializes the internal ApiClient
1366
+ * }
1367
+ * }
1368
+ *
1369
+ * // Usage in modular pattern
1370
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1371
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1372
+ *
1373
+ * const sdk = new UiPath(config);
1374
+ * await sdk.initialize();
1375
+ * const entities = new Entities(sdk);
1376
+ * ```
1377
+ */
1378
+ constructor(instance, headers) {
1379
+ // Private field - not visible via Object.keys() or any reflection
1380
+ _BaseService_apiClient.set(this, void 0);
1381
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1382
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1383
+ this.config = { folderKey };
1384
+ }
1385
+ /**
1386
+ * Gets a valid authentication token, refreshing if necessary.
1387
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1388
+ *
1389
+ * @returns Promise resolving to a valid access token string
1390
+ * @throws AuthenticationError if no token is available or refresh fails
1391
+ */
1392
+ async getValidAuthToken() {
1393
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1394
+ }
1395
+ /**
1396
+ * Creates a service accessor for pagination helpers
1397
+ * This allows pagination helpers to access protected methods without making them public
1398
+ */
1399
+ createPaginationServiceAccess() {
1400
+ return {
1401
+ get: (path, options) => this.get(path, options || {}),
1402
+ post: (path, body, options) => this.post(path, body, options || {}),
1403
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1404
+ };
1405
+ }
1406
+ async request(method, path, options = {}) {
1407
+ switch (method.toUpperCase()) {
1408
+ case 'GET':
1409
+ return this.get(path, options);
1410
+ case 'POST':
1411
+ return this.post(path, options.body, options);
1412
+ case 'PUT':
1413
+ return this.put(path, options.body, options);
1414
+ case 'PATCH':
1415
+ return this.patch(path, options.body, options);
1416
+ case 'DELETE':
1417
+ return this.delete(path, options);
1418
+ default:
1419
+ throw new Error(`Unsupported HTTP method: ${method}`);
1420
+ }
1421
+ }
1422
+ async requestWithSpec(spec) {
1423
+ if (!spec.method || !spec.url) {
1424
+ throw new Error('Request spec must include method and url');
1425
+ }
1426
+ return this.request(spec.method, spec.url, spec);
1427
+ }
1428
+ async get(path, options = {}) {
1429
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1430
+ return { data: response };
1431
+ }
1432
+ async post(path, data, options = {}) {
1433
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1434
+ return { data: response };
1435
+ }
1436
+ async put(path, data, options = {}) {
1437
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1438
+ return { data: response };
1439
+ }
1440
+ async patch(path, data, options = {}) {
1441
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1442
+ return { data: response };
1443
+ }
1444
+ async delete(path, options = {}) {
1445
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1446
+ return { data: response };
1447
+ }
1448
+ /**
1449
+ * Execute a request with cursor-based pagination
1450
+ */
1451
+ async requestWithPagination(method, path, paginationOptions, options) {
1452
+ const paginationType = options.pagination.paginationType;
1453
+ // Validate and prepare pagination parameters
1454
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1455
+ // Prepare request parameters based on pagination type
1456
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1457
+ // Route pagination state to wherever the API expects it (body for POST, URL for GET).
1458
+ // Caller-supplied options.body / options.params are respected as-is — the api-client
1459
+ // already handles params (URL) and body (request body) independently for every method.
1460
+ if (method.toUpperCase() === 'POST') {
1461
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1462
+ options.body = {
1463
+ ...existingBody,
1464
+ ...requestParams
1465
+ };
1466
+ }
1467
+ else {
1468
+ options.params = {
1469
+ ...options.params,
1470
+ ...requestParams
1471
+ };
1472
+ }
1473
+ // Make the request
1474
+ const response = await this.request(method, path, options);
1475
+ // Extract data from the response and create page result
1476
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1477
+ itemsField: options.pagination.itemsField,
1478
+ totalCountField: options.pagination.totalCountField,
1479
+ continuationTokenField: options.pagination.continuationTokenField
1480
+ });
1481
+ }
1482
+ /**
1483
+ * Validates and prepares pagination parameters from options
1484
+ */
1485
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1486
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1487
+ }
1488
+ /**
1489
+ * Prepares request parameters for pagination based on pagination type
1490
+ */
1491
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1492
+ const requestParams = {};
1493
+ let limitedPageSize;
1494
+ const paginationParams = paginationConfig?.paginationParams;
1495
+ switch (paginationType) {
1496
+ case PaginationType.OFFSET:
1497
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1498
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1499
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1500
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1501
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1502
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1503
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1504
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1505
+ const zeroBased = paginationParams?.zeroBased ?? false;
1506
+ requestParams[pageSizeParam] = limitedPageSize;
1507
+ if (convertToSkip) {
1508
+ if (params.pageNumber && params.pageNumber > 1) {
1509
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1510
+ }
1511
+ }
1512
+ else {
1513
+ const sdkPageNumber = params.pageNumber || 1;
1514
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1515
+ }
1516
+ {
1517
+ requestParams[countParam] = true;
1518
+ }
1519
+ break;
1520
+ case PaginationType.TOKEN:
1521
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1522
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1523
+ if (params.pageSize) {
1524
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1525
+ }
1526
+ if (params.continuationToken) {
1527
+ requestParams[tokenParam] = params.continuationToken;
1528
+ }
1529
+ break;
1530
+ }
1531
+ return requestParams;
1532
+ }
1533
+ /**
1534
+ * Creates a paginated response from API response
1535
+ */
1536
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1537
+ // Extract fields from response
1538
+ const itemsField = fields.itemsField ||
1539
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1540
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1541
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1542
+ // Extract items and metadata
1543
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1544
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1545
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1546
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1547
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1548
+ const continuationToken = response.data[continuationTokenField];
1549
+ // Determine if there are more pages
1550
+ const hasMore = this.determineHasMorePages(paginationType, {
1551
+ totalCount,
1552
+ pageSize: params.pageSize,
1553
+ currentPage: params.pageNumber || 1,
1554
+ itemsCount: items.length,
1555
+ continuationToken
1556
+ });
1557
+ // Create and return the page result
1558
+ return PaginationManager.createPaginatedResponse({
1559
+ pageInfo: {
1560
+ hasMore,
1561
+ totalCount,
1562
+ currentPage: params.pageNumber,
1563
+ pageSize: params.pageSize,
1564
+ continuationToken
1565
+ },
1566
+ type: paginationType,
1567
+ }, items);
1568
+ }
1569
+ /**
1570
+ * Determines if there are more pages based on pagination type and metadata
1571
+ */
1572
+ determineHasMorePages(paginationType, info) {
1573
+ switch (paginationType) {
1574
+ case PaginationType.OFFSET:
1575
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1576
+ // If totalCount is available, use it for precise calculation
1577
+ if (info.totalCount !== undefined) {
1578
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1579
+ }
1580
+ // Fallback when totalCount is not available
1581
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1582
+ return info.itemsCount === effectivePageSize;
1583
+ case PaginationType.TOKEN:
1584
+ return !!info.continuationToken;
1585
+ default:
1586
+ return false;
1587
+ }
1588
+ }
1589
+ }
1590
+ _BaseService_apiClient = new WeakMap();
1591
+
1592
+ /**
1593
+ * Base path constants for different services
1594
+ */
1595
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
1596
+
1597
+ /**
1598
+ * Governance Service Endpoints
1599
+ */
1600
+ /**
1601
+ * Governance Service Endpoints
1602
+ * Endpoints require an organization-admin caller
1603
+ */
1604
+ const GOVERNANCE_ENDPOINTS = {
1605
+ POLICY: {
1606
+ /** Policy evaluation traces (paginated). */
1607
+ TRACES: `${INSIGHTS_RTM_BASE}/Governance/policy/traces`,
1608
+ },
1609
+ OPERATION: {
1610
+ /** Aggregate governed-operation enforcement counts. */
1611
+ SUMMARY: `${INSIGHTS_RTM_BASE}/Governance/operation/summary`,
1612
+ },
1613
+ };
1614
+
1615
+ /**
1616
+ * SDK Telemetry constants.
1617
+ *
1618
+ * Only the SDK's identity (version, service name, role name, …) lives
1619
+ * here. The Application Insights connection string is injected into
1620
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
1621
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
1622
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
1623
+ * SDK's public API.
1624
+ */
1625
+ /** SDK version placeholder — patched by the SDK publish workflow. */
1626
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
1627
+
1628
+ /**
1629
+ * UiPath TypeScript SDK Telemetry
1630
+ *
1631
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
1632
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
1633
+ * does this independently, so events carry their own consumer's identity
1634
+ * and tenant context.
1635
+ */
1636
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
1637
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
1638
+ // from the `UiPath` constructor therefore wires up `@track` decorators
1639
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
1640
+ const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
1641
+ const track = createTrack(sdkClient);
1642
+ createTrackEvent(sdkClient);
1643
+
1644
+ /**
1645
+ * Service for inspecting governance policy enforcement on the UiPath platform.
1646
+ */
1647
+ class GovernanceService extends BaseService {
1648
+ /**
1649
+ * Gets per-policy enforcement decisions across the requested time range.
1650
+ *
1651
+ * Each result row represents one policy's verdict within a single governance enforcement event.
1652
+ * A single user action can produce multiple rows when multiple policies were consulted.
1653
+ * Results are ordered by event start time, descending.
1654
+ *
1655
+ * @param startTime - Inclusive lower bound on the trace start time.
1656
+ * @param options - Optional filters and pagination options
1657
+ * @returns Promise resolving to {@link NonPaginatedResponse} of {@link GovernancePolicyTrace}
1658
+ * without pagination options, or {@link PaginatedResponse} of
1659
+ * {@link GovernancePolicyTrace} when pagination options are used.
1660
+ *
1661
+ * @example
1662
+ * ```typescript
1663
+ * import { Governance, PolicyEvaluationResult } from '@uipath/uipath-typescript/governance';
1664
+ *
1665
+ * const governance = new Governance(sdk);
1666
+ *
1667
+ * // Get all policy traces from the specified start time
1668
+ * const recent = await governance.getPolicyTraces(new Date('2024-01-01'));
1669
+ * console.log(recent.items.length);
1670
+ *
1671
+ * // Get all denied decisions across the whole organization
1672
+ * const page1 = await governance.getPolicyTraces(
1673
+ * new Date('2024-01-01'),
1674
+ * {
1675
+ * endTime: new Date(),
1676
+ * evaluationResult: [PolicyEvaluationResult.Deny, PolicyEvaluationResult.SimulatedDeny],
1677
+ * fullOrganization: true,
1678
+ * pageSize: 25,
1679
+ * },
1680
+ * );
1681
+ *
1682
+ * if (page1.hasNextPage) {
1683
+ * const page2 = await governance.getPolicyTraces(
1684
+ * new Date('2024-01-01'),
1685
+ * { cursor: page1.nextCursor },
1686
+ * );
1687
+ * }
1688
+ * ```
1689
+ */
1690
+ async getPolicyTraces(startTime, options) {
1691
+ if (!startTime) {
1692
+ throw new ValidationError({ message: 'startTime is required for getPolicyTraces' });
1693
+ }
1694
+ const apiOptions = {
1695
+ ...options,
1696
+ startTime: startTime.toISOString(),
1697
+ endTime: options?.endTime?.toISOString(),
1698
+ };
1699
+ return PaginationHelpers.getAll({
1700
+ serviceAccess: this.createPaginationServiceAccess(),
1701
+ getEndpoint: () => GOVERNANCE_ENDPOINTS.POLICY.TRACES,
1702
+ method: HTTP_METHODS.POST,
1703
+ excludeFromPrefix: Object.keys(apiOptions),
1704
+ pagination: {
1705
+ paginationType: PaginationType.OFFSET,
1706
+ itemsField: GOVERNANCE_PAGINATION.ITEMS_FIELD,
1707
+ paginationParams: {
1708
+ pageSizeParam: GOVERNANCE_OFFSET_PARAMS.PAGE_SIZE_PARAM,
1709
+ offsetParam: GOVERNANCE_OFFSET_PARAMS.OFFSET_PARAM,
1710
+ countParam: GOVERNANCE_OFFSET_PARAMS.COUNT_PARAM,
1711
+ convertToSkip: false,
1712
+ zeroBased: true,
1713
+ },
1714
+ },
1715
+ }, apiOptions);
1716
+ }
1717
+ /**
1718
+ * Gets aggregate governance enforcement counts across the requested time range.
1719
+ *
1720
+ * Returns the total number of evaluations along with how many resolved to
1721
+ * `Allow`, `Deny`, or `NoOp`.
1722
+ *
1723
+ * @param startTime - Inclusive lower bound on the evaluation time.
1724
+ * @param options - Optional `endTime` upper bound and `fullOrganization` flag
1725
+ * @returns Promise resolving to {@link GovernanceOperationSummary}
1726
+ *
1727
+ * @example
1728
+ * ```typescript
1729
+ * import { Governance } from '@uipath/uipath-typescript/governance';
1730
+ *
1731
+ * const governance = new Governance(sdk);
1732
+ *
1733
+ * // Get operation summary from the specified start time to right now
1734
+ * const summary = await governance.getOperationSummary(new Date('2024-01-01'));
1735
+ * console.log(summary.totalEvaluations, summary.allowedCount, summary.deniedCount, summary.noOpCount);
1736
+ *
1737
+ * // Bounded range across the whole organization
1738
+ * const ranged = await governance.getOperationSummary(
1739
+ * new Date('2024-01-01'),
1740
+ * { endTime: new Date(), fullOrganization: true },
1741
+ * );
1742
+ * ```
1743
+ */
1744
+ async getOperationSummary(startTime, options) {
1745
+ if (!startTime) {
1746
+ throw new ValidationError({ message: 'startTime is required for getOperationSummary' });
1747
+ }
1748
+ const body = filterUndefined({
1749
+ startTime: startTime.toISOString(),
1750
+ endTime: options?.endTime?.toISOString(),
1751
+ fullOrganization: options?.fullOrganization,
1752
+ });
1753
+ const response = await this.post(GOVERNANCE_ENDPOINTS.OPERATION.SUMMARY, body);
1754
+ const data = response.data;
1755
+ return {
1756
+ totalEvaluations: data.totalEvaluations ?? 0,
1757
+ allowedCount: data.allow ?? 0,
1758
+ deniedCount: data.deny ?? 0,
1759
+ noOpCount: data.noOp ?? 0,
1760
+ };
1761
+ }
1762
+ }
1763
+ __decorate([
1764
+ track('Governance.GetPolicyTraces')
1765
+ ], GovernanceService.prototype, "getPolicyTraces", null);
1766
+ __decorate([
1767
+ track('Governance.GetOperationSummary')
1768
+ ], GovernanceService.prototype, "getOperationSummary", null);
1769
+
1770
+ /**
1771
+ * Governance Service Types
1772
+ *
1773
+ * Public types exposed via `@uipath/uipath-typescript/governance`.
1774
+ */
1775
+ var PolicyEvaluationResult;
1776
+ (function (PolicyEvaluationResult) {
1777
+ /** Active policy permitted the action. */
1778
+ PolicyEvaluationResult["Allow"] = "Allow";
1779
+ /** Active policy blocked the action. */
1780
+ PolicyEvaluationResult["Deny"] = "Deny";
1781
+ /** Simulated (NoOp) policy would have permitted the action. */
1782
+ PolicyEvaluationResult["SimulatedAllow"] = "SimulatedAllow";
1783
+ /** Simulated (NoOp) policy would have blocked the action. */
1784
+ PolicyEvaluationResult["SimulatedDeny"] = "SimulatedDeny";
1785
+ })(PolicyEvaluationResult || (PolicyEvaluationResult = {}));
1786
+
1787
+ export { GovernanceService as Governance, PolicyEvaluationResult };