@uipath/uipath-typescript 1.3.10 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/agent-memory/index.cjs +1765 -0
  2. package/dist/agent-memory/index.d.ts +588 -0
  3. package/dist/agent-memory/index.mjs +1763 -0
  4. package/dist/agents/index.cjs +1726 -0
  5. package/dist/agents/index.d.ts +502 -0
  6. package/dist/agents/index.mjs +1724 -0
  7. package/dist/assets/index.cjs +155 -30
  8. package/dist/assets/index.d.ts +84 -5
  9. package/dist/assets/index.mjs +155 -30
  10. package/dist/attachments/index.cjs +37 -6
  11. package/dist/attachments/index.d.ts +1 -0
  12. package/dist/attachments/index.mjs +37 -6
  13. package/dist/buckets/index.cjs +37 -6
  14. package/dist/buckets/index.d.ts +1 -0
  15. package/dist/buckets/index.mjs +37 -6
  16. package/dist/cases/index.cjs +192 -10
  17. package/dist/cases/index.d.ts +208 -7
  18. package/dist/cases/index.mjs +192 -11
  19. package/dist/conversational-agent/index.cjs +124 -57
  20. package/dist/conversational-agent/index.d.ts +190 -122
  21. package/dist/conversational-agent/index.mjs +124 -57
  22. package/dist/core/index.cjs +413 -105
  23. package/dist/core/index.d.ts +15 -0
  24. package/dist/core/index.mjs +413 -105
  25. package/dist/entities/index.cjs +135 -70
  26. package/dist/entities/index.d.ts +146 -45
  27. package/dist/entities/index.mjs +135 -70
  28. package/dist/feedback/index.cjs +37 -6
  29. package/dist/feedback/index.d.ts +1 -0
  30. package/dist/feedback/index.mjs +37 -6
  31. package/dist/governance/index.cjs +1782 -0
  32. package/dist/governance/index.d.ts +598 -0
  33. package/dist/governance/index.mjs +1780 -0
  34. package/dist/index.cjs +1050 -291
  35. package/dist/index.d.ts +1313 -134
  36. package/dist/index.mjs +1050 -292
  37. package/dist/index.umd.js +4546 -3770
  38. package/dist/jobs/index.cjs +37 -6
  39. package/dist/jobs/index.d.ts +1 -0
  40. package/dist/jobs/index.mjs +37 -6
  41. package/dist/maestro-processes/index.cjs +224 -18
  42. package/dist/maestro-processes/index.d.ts +221 -9
  43. package/dist/maestro-processes/index.mjs +224 -18
  44. package/dist/processes/index.cjs +37 -6
  45. package/dist/processes/index.d.ts +1 -0
  46. package/dist/processes/index.mjs +37 -6
  47. package/dist/queues/index.cjs +37 -6
  48. package/dist/queues/index.d.ts +1 -0
  49. package/dist/queues/index.mjs +37 -6
  50. package/dist/tasks/index.cjs +37 -6
  51. package/dist/tasks/index.d.ts +1 -0
  52. package/dist/tasks/index.mjs +37 -6
  53. package/dist/traces/index.cjs +1933 -0
  54. package/dist/traces/index.d.ts +566 -0
  55. package/dist/traces/index.mjs +1931 -0
  56. package/package.json +42 -2
@@ -0,0 +1,1763 @@
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
+ * OData OFFSET pagination parameter names (ODATA-style)
922
+ */
923
+ const ODATA_OFFSET_PARAMS = {
924
+ /** OData page size parameter name */
925
+ PAGE_SIZE_PARAM: '$top',
926
+ /** OData offset parameter name */
927
+ OFFSET_PARAM: '$skip',
928
+ /** OData count parameter name */
929
+ COUNT_PARAM: '$count'
930
+ };
931
+ /**
932
+ * Bucket TOKEN pagination parameter names
933
+ */
934
+ const BUCKET_TOKEN_PARAMS = {
935
+ /** Bucket page size parameter name */
936
+ PAGE_SIZE_PARAM: 'takeHint',
937
+ /** Bucket token parameter name */
938
+ TOKEN_PARAM: 'continuationToken'
939
+ };
940
+
941
+ /**
942
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
943
+ * Returns the original value if parsing fails.
944
+ */
945
+ /**
946
+ * Adds a prefix to specified keys in an object, returning a new object.
947
+ * Only the provided keys are prefixed; all others are left unchanged.
948
+ *
949
+ * @param obj The source object
950
+ * @param prefix The prefix to add (e.g., '$')
951
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
952
+ * @returns A new object with specified keys prefixed
953
+ *
954
+ * @example
955
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
956
+ */
957
+ function addPrefixToKeys(obj, prefix, keys) {
958
+ const result = {};
959
+ for (const [key, value] of Object.entries(obj)) {
960
+ if (keys.includes(key)) {
961
+ result[`${prefix}${key}`] = value;
962
+ }
963
+ else {
964
+ result[key] = value;
965
+ }
966
+ }
967
+ return result;
968
+ }
969
+
970
+ /**
971
+ * Constants used throughout the pagination system
972
+ */
973
+ /** Maximum number of items that can be requested in a single page */
974
+ const MAX_PAGE_SIZE = 1000;
975
+ /** Default page size when jumpToPage is used without specifying pageSize */
976
+ const DEFAULT_PAGE_SIZE = 50;
977
+ /** Default field name for items in a paginated response */
978
+ const DEFAULT_ITEMS_FIELD = 'value';
979
+ /** Default field name for total count in a paginated response */
980
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
981
+ /**
982
+ * Limits the page size to the maximum allowed value
983
+ * @param pageSize - Requested page size
984
+ * @returns Limited page size value
985
+ */
986
+ function getLimitedPageSize(pageSize) {
987
+ if (pageSize === undefined || pageSize === null) {
988
+ return DEFAULT_PAGE_SIZE;
989
+ }
990
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
991
+ }
992
+
993
+ /**
994
+ * Helper functions for pagination that can be used across services
995
+ */
996
+ class PaginationHelpers {
997
+ /**
998
+ * Checks if any pagination parameters are provided
999
+ *
1000
+ * @param options - The options object to check
1001
+ * @returns True if any pagination parameter is defined, false otherwise
1002
+ */
1003
+ static hasPaginationParameters(options = {}) {
1004
+ const { cursor, pageSize, jumpToPage } = options;
1005
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1006
+ }
1007
+ /**
1008
+ * Parse a pagination cursor string into cursor data
1009
+ */
1010
+ static parseCursor(cursorString) {
1011
+ try {
1012
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1013
+ return cursorData;
1014
+ }
1015
+ catch {
1016
+ throw new Error('Invalid pagination cursor');
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Validates cursor format and structure
1021
+ *
1022
+ * @param paginationOptions - The pagination options containing the cursor
1023
+ * @param paginationType - Optional pagination type to validate against
1024
+ */
1025
+ static validateCursor(paginationOptions, paginationType) {
1026
+ if (paginationOptions.cursor !== undefined) {
1027
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1028
+ throw new Error('cursor must contain a valid cursor string');
1029
+ }
1030
+ try {
1031
+ // Try to parse the cursor to validate it
1032
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1033
+ // If type is provided, validate cursor contains expected type information
1034
+ if (paginationType) {
1035
+ if (!cursorData.type) {
1036
+ throw new Error('Invalid cursor: missing pagination type');
1037
+ }
1038
+ // Check pagination type compatibility
1039
+ if (cursorData.type !== paginationType) {
1040
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1041
+ }
1042
+ }
1043
+ }
1044
+ catch (error) {
1045
+ if (error instanceof Error) {
1046
+ // If it's already our error with specific message, pass it through
1047
+ if (error.message.startsWith('Invalid cursor') ||
1048
+ error.message.startsWith('Pagination type mismatch')) {
1049
+ throw error;
1050
+ }
1051
+ }
1052
+ throw new Error('Invalid pagination cursor format');
1053
+ }
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Comprehensive validation for pagination options
1058
+ *
1059
+ * @param options - The pagination options to validate
1060
+ * @param paginationType - The pagination type these options will be used with
1061
+ * @returns Processed pagination parameters ready for use
1062
+ */
1063
+ static validatePaginationOptions(options, paginationType) {
1064
+ // Validate pageSize
1065
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1066
+ throw new Error('pageSize must be a positive number');
1067
+ }
1068
+ // Validate jumpToPage
1069
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1070
+ throw new Error('jumpToPage must be a positive number');
1071
+ }
1072
+ // Validate cursor
1073
+ PaginationHelpers.validateCursor(options, paginationType);
1074
+ // Validate service compatibility
1075
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1076
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1077
+ }
1078
+ // Get processed parameters
1079
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1080
+ }
1081
+ /**
1082
+ * Convert a unified pagination options to service-specific parameters
1083
+ */
1084
+ static getRequestParameters(options, paginationType) {
1085
+ // Handle jumpToPage
1086
+ if (options.jumpToPage !== undefined) {
1087
+ const jumpToPageOptions = {
1088
+ pageSize: options.pageSize,
1089
+ pageNumber: options.jumpToPage
1090
+ };
1091
+ return filterUndefined(jumpToPageOptions);
1092
+ }
1093
+ // If no cursor is provided, it's a first page request
1094
+ if (!options.cursor) {
1095
+ const firstPageOptions = {
1096
+ pageSize: options.pageSize,
1097
+ // Only set pageNumber for OFFSET pagination
1098
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1099
+ };
1100
+ return filterUndefined(firstPageOptions);
1101
+ }
1102
+ // Parse the cursor
1103
+ try {
1104
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1105
+ const cursorBasedOptions = {
1106
+ pageSize: cursorData.pageSize || options.pageSize,
1107
+ pageNumber: cursorData.pageNumber,
1108
+ continuationToken: cursorData.continuationToken,
1109
+ type: cursorData.type,
1110
+ };
1111
+ return filterUndefined(cursorBasedOptions);
1112
+ }
1113
+ catch {
1114
+ throw new Error('Invalid pagination cursor');
1115
+ }
1116
+ }
1117
+ /**
1118
+ * Helper method for paginated resource retrieval
1119
+ *
1120
+ * @param params - Parameters for pagination
1121
+ * @returns Promise resolving to a paginated result
1122
+ */
1123
+ static async getAllPaginated(params) {
1124
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1125
+ const endpoint = getEndpoint(folderId);
1126
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1127
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1128
+ headers,
1129
+ params: additionalParams,
1130
+ pagination: {
1131
+ paginationType: options.paginationType || PaginationType.OFFSET,
1132
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1133
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1134
+ continuationTokenField: options.continuationTokenField,
1135
+ paginationParams: options.paginationParams
1136
+ }
1137
+ });
1138
+ // Parse items - automatically handle JSON string responses
1139
+ const rawItems = paginatedResponse.items;
1140
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1141
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1142
+ return {
1143
+ ...paginatedResponse,
1144
+ items: transformedItems
1145
+ };
1146
+ }
1147
+ /**
1148
+ * Helper method for non-paginated resource retrieval
1149
+ *
1150
+ * @param params - Parameters for non-paginated resource retrieval
1151
+ * @returns Promise resolving to an object with data and totalCount
1152
+ */
1153
+ static async getAllNonPaginated(params) {
1154
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1155
+ // Set default field names
1156
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1157
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1158
+ // Determine endpoint and headers based on folderId
1159
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1160
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1161
+ // Make the API call based on method
1162
+ let response;
1163
+ if (method === HTTP_METHODS.POST) {
1164
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1165
+ }
1166
+ else {
1167
+ response = await serviceAccess.get(endpoint, {
1168
+ params: additionalParams,
1169
+ headers
1170
+ });
1171
+ }
1172
+ // Extract and transform items from response
1173
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1174
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1175
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
1176
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1177
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1178
+ // Parse items - automatically handle JSON string responses
1179
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1180
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1181
+ return {
1182
+ items,
1183
+ totalCount
1184
+ };
1185
+ }
1186
+ /**
1187
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1188
+ *
1189
+ * @param config - Configuration for the getAll operation
1190
+ * @param options - Request options including pagination parameters
1191
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1192
+ */
1193
+ static async getAll(config, options) {
1194
+ const optionsWithDefaults = options || {};
1195
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1196
+ // Determine if pagination is requested
1197
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1198
+ // Process parameters (custom processing if provided, otherwise default)
1199
+ let processedOptions = restOptions;
1200
+ if (config.processParametersFn) {
1201
+ processedOptions = config.processParametersFn(restOptions, folderId);
1202
+ }
1203
+ // Apply ODATA prefix to keys (excluding specified keys)
1204
+ const excludeKeys = config.excludeFromPrefix || [];
1205
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1206
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1207
+ // Default pagination options
1208
+ const paginationOptions = {
1209
+ paginationType: PaginationType.OFFSET,
1210
+ itemsField: DEFAULT_ITEMS_FIELD,
1211
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1212
+ ...config.pagination
1213
+ };
1214
+ // Paginated flow
1215
+ if (isPaginationRequested) {
1216
+ return PaginationHelpers.getAllPaginated({
1217
+ serviceAccess: config.serviceAccess,
1218
+ getEndpoint: config.getEndpoint,
1219
+ folderId,
1220
+ headers: config.headers,
1221
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
1222
+ additionalParams: prefixedOptions,
1223
+ transformFn: config.transformFn,
1224
+ method: config.method,
1225
+ options: {
1226
+ ...paginationOptions,
1227
+ paginationParams: config.pagination?.paginationParams
1228
+ }
1229
+ }); // Type assertion needed due to conditional return
1230
+ }
1231
+ // Non-paginated flow
1232
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1233
+ return PaginationHelpers.getAllNonPaginated({
1234
+ serviceAccess: config.serviceAccess,
1235
+ getAllEndpoint: config.getEndpoint(),
1236
+ getByFolderEndpoint: byFolderEndpoint,
1237
+ folderId,
1238
+ headers: config.headers,
1239
+ additionalParams: prefixedOptions,
1240
+ transformFn: config.transformFn,
1241
+ method: config.method,
1242
+ options: {
1243
+ itemsField: paginationOptions.itemsField,
1244
+ totalCountField: paginationOptions.totalCountField
1245
+ }
1246
+ });
1247
+ }
1248
+ }
1249
+
1250
+ /**
1251
+ * SDK Internals Registry - Internal registry for SDK instances
1252
+ *
1253
+ * This class is NOT exported in the public API.
1254
+ * It provides a secure way to share SDK internals between
1255
+ * the UiPath class and service classes without exposing them publicly.
1256
+ *
1257
+ * @internal
1258
+ */
1259
+ // Global symbol key to ensure WeakMap is shared across module instances
1260
+ // This prevents issues when core and service modules are bundled separately
1261
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1262
+ // Get or create the global WeakMap store
1263
+ const getGlobalStore = () => {
1264
+ const globalObj = globalThis;
1265
+ if (!globalObj[REGISTRY_KEY]) {
1266
+ globalObj[REGISTRY_KEY] = new WeakMap();
1267
+ }
1268
+ return globalObj[REGISTRY_KEY];
1269
+ };
1270
+ /**
1271
+ * Internal registry for SDK private components.
1272
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1273
+ * garbage collected when the SDK instance is no longer referenced.
1274
+ *
1275
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1276
+ * across separately bundled modules (core, entities, tasks, etc.).
1277
+ *
1278
+ * @internal - Not exported in public API
1279
+ */
1280
+ class SDKInternalsRegistry {
1281
+ // Use global store to ensure sharing across module bundles
1282
+ static get store() {
1283
+ return getGlobalStore();
1284
+ }
1285
+ /**
1286
+ * Register SDK instance internals
1287
+ * Called by UiPath constructor
1288
+ */
1289
+ static set(instance, internals) {
1290
+ this.store.set(instance, internals);
1291
+ }
1292
+ /**
1293
+ * Retrieve SDK instance internals
1294
+ * Called by BaseService constructor
1295
+ */
1296
+ static get(instance) {
1297
+ const internals = this.store.get(instance);
1298
+ if (!internals) {
1299
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1300
+ }
1301
+ return internals;
1302
+ }
1303
+ }
1304
+
1305
+ var _BaseService_apiClient;
1306
+ /**
1307
+ * Base class for all UiPath SDK services.
1308
+ *
1309
+ * Provides common functionality for authentication, configuration, and API communication.
1310
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1311
+ *
1312
+ * This class implements the dependency injection pattern where services receive a configured
1313
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1314
+ * including authentication token management.
1315
+ *
1316
+ * @remarks
1317
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1318
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1319
+ *
1320
+ */
1321
+ class BaseService {
1322
+ /**
1323
+ * Creates a base service instance with dependency injection.
1324
+ *
1325
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1326
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1327
+ * and token management internally.
1328
+ *
1329
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1330
+ * Services receive this via dependency injection in the modular pattern.
1331
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1332
+ * CAS external-app auth)
1333
+ *
1334
+ * @example
1335
+ * ```typescript
1336
+ * // Services automatically call this via super()
1337
+ * export class EntityService extends BaseService {
1338
+ * constructor(instance: IUiPath) {
1339
+ * super(instance); // Initializes the internal ApiClient
1340
+ * }
1341
+ * }
1342
+ *
1343
+ * // Usage in modular pattern
1344
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1345
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1346
+ *
1347
+ * const sdk = new UiPath(config);
1348
+ * await sdk.initialize();
1349
+ * const entities = new Entities(sdk);
1350
+ * ```
1351
+ */
1352
+ constructor(instance, headers) {
1353
+ // Private field - not visible via Object.keys() or any reflection
1354
+ _BaseService_apiClient.set(this, void 0);
1355
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1356
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1357
+ this.config = { folderKey };
1358
+ }
1359
+ /**
1360
+ * Gets a valid authentication token, refreshing if necessary.
1361
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1362
+ *
1363
+ * @returns Promise resolving to a valid access token string
1364
+ * @throws AuthenticationError if no token is available or refresh fails
1365
+ */
1366
+ async getValidAuthToken() {
1367
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1368
+ }
1369
+ /**
1370
+ * Creates a service accessor for pagination helpers
1371
+ * This allows pagination helpers to access protected methods without making them public
1372
+ */
1373
+ createPaginationServiceAccess() {
1374
+ return {
1375
+ get: (path, options) => this.get(path, options || {}),
1376
+ post: (path, body, options) => this.post(path, body, options || {}),
1377
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1378
+ };
1379
+ }
1380
+ async request(method, path, options = {}) {
1381
+ switch (method.toUpperCase()) {
1382
+ case 'GET':
1383
+ return this.get(path, options);
1384
+ case 'POST':
1385
+ return this.post(path, options.body, options);
1386
+ case 'PUT':
1387
+ return this.put(path, options.body, options);
1388
+ case 'PATCH':
1389
+ return this.patch(path, options.body, options);
1390
+ case 'DELETE':
1391
+ return this.delete(path, options);
1392
+ default:
1393
+ throw new Error(`Unsupported HTTP method: ${method}`);
1394
+ }
1395
+ }
1396
+ async requestWithSpec(spec) {
1397
+ if (!spec.method || !spec.url) {
1398
+ throw new Error('Request spec must include method and url');
1399
+ }
1400
+ return this.request(spec.method, spec.url, spec);
1401
+ }
1402
+ async get(path, options = {}) {
1403
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1404
+ return { data: response };
1405
+ }
1406
+ async post(path, data, options = {}) {
1407
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1408
+ return { data: response };
1409
+ }
1410
+ async put(path, data, options = {}) {
1411
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1412
+ return { data: response };
1413
+ }
1414
+ async patch(path, data, options = {}) {
1415
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1416
+ return { data: response };
1417
+ }
1418
+ async delete(path, options = {}) {
1419
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1420
+ return { data: response };
1421
+ }
1422
+ /**
1423
+ * Execute a request with cursor-based pagination
1424
+ */
1425
+ async requestWithPagination(method, path, paginationOptions, options) {
1426
+ const paginationType = options.pagination.paginationType;
1427
+ // Validate and prepare pagination parameters
1428
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1429
+ // Prepare request parameters based on pagination type
1430
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1431
+ // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1432
+ if (method.toUpperCase() === 'POST') {
1433
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1434
+ options.body = {
1435
+ ...existingBody,
1436
+ ...options.params,
1437
+ ...requestParams
1438
+ };
1439
+ options.params = undefined;
1440
+ }
1441
+ else {
1442
+ // Merge pagination parameters with existing parameters
1443
+ options.params = {
1444
+ ...options.params,
1445
+ ...requestParams
1446
+ };
1447
+ }
1448
+ // Make the request
1449
+ const response = await this.request(method, path, options);
1450
+ // Extract data from the response and create page result
1451
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1452
+ itemsField: options.pagination.itemsField,
1453
+ totalCountField: options.pagination.totalCountField,
1454
+ continuationTokenField: options.pagination.continuationTokenField
1455
+ });
1456
+ }
1457
+ /**
1458
+ * Validates and prepares pagination parameters from options
1459
+ */
1460
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1461
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1462
+ }
1463
+ /**
1464
+ * Prepares request parameters for pagination based on pagination type
1465
+ */
1466
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1467
+ const requestParams = {};
1468
+ let limitedPageSize;
1469
+ const paginationParams = paginationConfig?.paginationParams;
1470
+ switch (paginationType) {
1471
+ case PaginationType.OFFSET:
1472
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1473
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1474
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1475
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1476
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1477
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1478
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1479
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
1480
+ const zeroBased = paginationParams?.zeroBased ?? false;
1481
+ requestParams[pageSizeParam] = limitedPageSize;
1482
+ if (convertToSkip) {
1483
+ if (params.pageNumber && params.pageNumber > 1) {
1484
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1485
+ }
1486
+ }
1487
+ else {
1488
+ const sdkPageNumber = params.pageNumber || 1;
1489
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
1490
+ }
1491
+ {
1492
+ requestParams[countParam] = true;
1493
+ }
1494
+ break;
1495
+ case PaginationType.TOKEN:
1496
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1497
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1498
+ if (params.pageSize) {
1499
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1500
+ }
1501
+ if (params.continuationToken) {
1502
+ requestParams[tokenParam] = params.continuationToken;
1503
+ }
1504
+ break;
1505
+ }
1506
+ return requestParams;
1507
+ }
1508
+ /**
1509
+ * Creates a paginated response from API response
1510
+ */
1511
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1512
+ // Extract fields from response
1513
+ const itemsField = fields.itemsField ||
1514
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1515
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1516
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1517
+ // Extract items and metadata
1518
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
1519
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
1520
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
1521
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1522
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1523
+ const continuationToken = response.data[continuationTokenField];
1524
+ // Determine if there are more pages
1525
+ const hasMore = this.determineHasMorePages(paginationType, {
1526
+ totalCount,
1527
+ pageSize: params.pageSize,
1528
+ currentPage: params.pageNumber || 1,
1529
+ itemsCount: items.length,
1530
+ continuationToken
1531
+ });
1532
+ // Create and return the page result
1533
+ return PaginationManager.createPaginatedResponse({
1534
+ pageInfo: {
1535
+ hasMore,
1536
+ totalCount,
1537
+ currentPage: params.pageNumber,
1538
+ pageSize: params.pageSize,
1539
+ continuationToken
1540
+ },
1541
+ type: paginationType,
1542
+ }, items);
1543
+ }
1544
+ /**
1545
+ * Determines if there are more pages based on pagination type and metadata
1546
+ */
1547
+ determineHasMorePages(paginationType, info) {
1548
+ switch (paginationType) {
1549
+ case PaginationType.OFFSET:
1550
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1551
+ // If totalCount is available, use it for precise calculation
1552
+ if (info.totalCount !== undefined) {
1553
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1554
+ }
1555
+ // Fallback when totalCount is not available
1556
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1557
+ return info.itemsCount === effectivePageSize;
1558
+ case PaginationType.TOKEN:
1559
+ return !!info.continuationToken;
1560
+ default:
1561
+ return false;
1562
+ }
1563
+ }
1564
+ }
1565
+ _BaseService_apiClient = new WeakMap();
1566
+
1567
+ /**
1568
+ * Base path constants for different services
1569
+ */
1570
+ const INSIGHTS_RTM_BASE = 'insightsrtm_';
1571
+
1572
+ /**
1573
+ * Agent Memory Service Endpoints
1574
+ */
1575
+ const MEMORY_ENDPOINTS = {
1576
+ /** Time-series of agent-memory state counts bucketed across the requested window. */
1577
+ GET_TIMELINE: `${INSIGHTS_RTM_BASE}/Traceview/memoryTimeline`,
1578
+ /** Time-series of memory-call counts bucketed across the requested window. */
1579
+ GET_CALLS_TIMELINE: `${INSIGHTS_RTM_BASE}/Traceview/memoryCallsTimeline`,
1580
+ /** Top-N memory spaces ranked by memory count over the requested window. */
1581
+ GET_TOP_SPACES: `${INSIGHTS_RTM_BASE}/Traceview/topMemorySpaces`,
1582
+ };
1583
+
1584
+ /**
1585
+ * SDK Telemetry constants.
1586
+ *
1587
+ * Only the SDK's identity (version, service name, role name, …) lives
1588
+ * here. The Application Insights connection string is injected into
1589
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
1590
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
1591
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
1592
+ * SDK's public API.
1593
+ */
1594
+ /** SDK version placeholder — patched by the SDK publish workflow. */
1595
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
1596
+
1597
+ /**
1598
+ * UiPath TypeScript SDK Telemetry
1599
+ *
1600
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
1601
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
1602
+ * does this independently, so events carry their own consumer's identity
1603
+ * and tenant context.
1604
+ */
1605
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
1606
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
1607
+ // from the `UiPath` constructor therefore wires up `@track` decorators
1608
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
1609
+ const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
1610
+ const track = createTrack(sdkClient);
1611
+ createTrackEvent(sdkClient);
1612
+
1613
+ /**
1614
+ * Service for managing UiPath Agent Memory.
1615
+ */
1616
+ class MemoryService extends BaseService {
1617
+ /**
1618
+ * Gets agent memory state over time, with optional filters.
1619
+ *
1620
+ * @param options - Optional time window and scope filters
1621
+ * @returns Promise resolving to an array of {@link AgentMemoryGetTimelineResponse}, one per time bucket.
1622
+ * @example
1623
+ * ```typescript
1624
+ * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory';
1625
+ *
1626
+ * const memory = new AgentMemory(sdk);
1627
+ *
1628
+ * // Last 24 hours (default window)
1629
+ * const timeline = await memory.getTimeline();
1630
+ * console.log(timeline[0]?.inMemoryCount);
1631
+ * ```
1632
+ * @example
1633
+ * ```typescript
1634
+ * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory';
1635
+ *
1636
+ * // Scoped to one agent in one folder, runtime executions only
1637
+ * const scoped = await memory.getTimeline({
1638
+ * startTime: new Date('2026-05-01T00:00:00Z'),
1639
+ * endTime: new Date('2026-06-01T00:00:00Z'),
1640
+ * agentId: '<agentId>',
1641
+ * folderKeys: ['<folderKey>'],
1642
+ * executionType: AgentMemoryExecutionType.Runtime,
1643
+ * });
1644
+ * ```
1645
+ */
1646
+ async getTimeline(options) {
1647
+ const body = this.buildMemoryFilterBody(options);
1648
+ const response = await this.post(MEMORY_ENDPOINTS.GET_TIMELINE, body);
1649
+ return response.data.data;
1650
+ }
1651
+ /**
1652
+ * Gets agent memory-access counts over time, with optional filters.
1653
+ *
1654
+ * @param options - Optional time window and scope filters
1655
+ * @returns Promise resolving to an array of {@link AgentMemoryGetCallsTimelineResponse}, one per time bucket.
1656
+ * @example
1657
+ * ```typescript
1658
+ * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory';
1659
+ *
1660
+ * const memory = new AgentMemory(sdk);
1661
+ *
1662
+ * // Last 24 hours (default window)
1663
+ * const timeline = await memory.getCallsTimeline();
1664
+ * console.log(timeline[0]?.memoryCallsCount);
1665
+ * ```
1666
+ * @example
1667
+ * ```typescript
1668
+ * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory';
1669
+ *
1670
+ * // Scoped to one agent in one folder, runtime executions only
1671
+ * const scoped = await memory.getCallsTimeline({
1672
+ * startTime: new Date('2026-05-01T00:00:00Z'),
1673
+ * endTime: new Date('2026-06-01T00:00:00Z'),
1674
+ * agentId: '<agentId>',
1675
+ * folderKeys: ['<folderKey>'],
1676
+ * executionType: AgentMemoryExecutionType.Runtime,
1677
+ * });
1678
+ * ```
1679
+ */
1680
+ async getCallsTimeline(options) {
1681
+ const body = this.buildMemoryFilterBody(options);
1682
+ const response = await this.post(MEMORY_ENDPOINTS.GET_CALLS_TIMELINE, body);
1683
+ return response.data.data;
1684
+ }
1685
+ /**
1686
+ * Gets the top memory spaces by memory count, with optional filters
1687
+ *
1688
+ * @param options - Optional limit, time window, and scope filters
1689
+ * @returns Promise resolving to an array of {@link AgentMemoryGetTopSpacesResponse}, ranked by memory count.
1690
+ * @example
1691
+ * ```typescript
1692
+ * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory';
1693
+ *
1694
+ * const memory = new AgentMemory(sdk);
1695
+ *
1696
+ * // Top 5 memory spaces (default limit and window)
1697
+ * const top = await memory.getTopSpaces();
1698
+ * console.log(top[0]?.memorySpaceName, top[0]?.memoryCount);
1699
+ * ```
1700
+ * @example
1701
+ * ```typescript
1702
+ * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory';
1703
+ *
1704
+ * // Top 10 spaces for one folder over an explicit window, runtime executions only
1705
+ * const topScoped = await memory.getTopSpaces({
1706
+ * startTime: new Date('2026-05-01T00:00:00Z'),
1707
+ * endTime: new Date('2026-06-01T00:00:00Z'),
1708
+ * folderKeys: ['<folderKey>'],
1709
+ * executionType: AgentMemoryExecutionType.Runtime,
1710
+ * limit: 10,
1711
+ * });
1712
+ * ```
1713
+ */
1714
+ async getTopSpaces(options) {
1715
+ const body = this.buildMemoryFilterBody(options);
1716
+ if (options?.limit !== undefined)
1717
+ body.limit = options.limit;
1718
+ const response = await this.post(MEMORY_ENDPOINTS.GET_TOP_SPACES, body);
1719
+ return response.data.data;
1720
+ }
1721
+ buildMemoryFilterBody(options) {
1722
+ const body = {};
1723
+ if (options?.startTime !== undefined)
1724
+ body.startTime = options.startTime.toISOString();
1725
+ if (options?.endTime !== undefined)
1726
+ body.endTime = options.endTime.toISOString();
1727
+ if (options?.agentId !== undefined)
1728
+ body.agentId = options.agentId;
1729
+ if (options?.agentVersion !== undefined)
1730
+ body.agentVersion = options.agentVersion;
1731
+ if (options?.folderKeys !== undefined)
1732
+ body.folderKeys = options.folderKeys;
1733
+ if (options?.executionType !== undefined)
1734
+ body.executionType = options.executionType;
1735
+ return body;
1736
+ }
1737
+ }
1738
+ __decorate([
1739
+ track('AgentMemory.GetTimeline')
1740
+ ], MemoryService.prototype, "getTimeline", null);
1741
+ __decorate([
1742
+ track('AgentMemory.GetCallsTimeline')
1743
+ ], MemoryService.prototype, "getCallsTimeline", null);
1744
+ __decorate([
1745
+ track('AgentMemory.GetTopSpaces')
1746
+ ], MemoryService.prototype, "getTopSpaces", null);
1747
+
1748
+ /**
1749
+ * Types for the Agent Memory metrics service.
1750
+ */
1751
+ /**
1752
+ * Execution kind to filter Agent Memory queries by. Omit to include both
1753
+ * Debug and Runtime executions.
1754
+ */
1755
+ var AgentMemoryExecutionType;
1756
+ (function (AgentMemoryExecutionType) {
1757
+ /** Executions produced during agent debugging sessions. */
1758
+ AgentMemoryExecutionType["Debug"] = "Debug";
1759
+ /** Executions produced during production runtime. */
1760
+ AgentMemoryExecutionType["Runtime"] = "Runtime";
1761
+ })(AgentMemoryExecutionType || (AgentMemoryExecutionType = {}));
1762
+
1763
+ export { MemoryService as AgentMemory, AgentMemoryExecutionType };