@uipath/uipath-typescript 1.3.10 → 1.3.11

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.
@@ -0,0 +1,1900 @@
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
+
721
+ /**
722
+ * Base64 encoding/decoding
723
+ */
724
+ /**
725
+ * Encodes a string to base64
726
+ * @param str - The string to encode
727
+ * @returns Base64 encoded string
728
+ */
729
+ function encodeBase64(str) {
730
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
731
+ const encoder = new TextEncoder();
732
+ const data = encoder.encode(str);
733
+ // Convert Uint8Array to base64
734
+ if (isBrowser) {
735
+ // Browser environment
736
+ // Convert Uint8Array to binary string then to base64
737
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
738
+ return btoa(binaryString);
739
+ }
740
+ else {
741
+ // Node.js environment
742
+ return Buffer.from(data).toString('base64');
743
+ }
744
+ }
745
+ /**
746
+ * Decodes a base64 string
747
+ * @param base64 - The base64 string to decode
748
+ * @returns Decoded string
749
+ */
750
+ function decodeBase64(base64) {
751
+ let bytes;
752
+ if (isBrowser) {
753
+ // Browser environment
754
+ const binaryString = atob(base64);
755
+ bytes = new Uint8Array(binaryString.length);
756
+ for (let i = 0; i < binaryString.length; i++) {
757
+ bytes[i] = binaryString.charCodeAt(i);
758
+ }
759
+ }
760
+ else {
761
+ // Node.js environment
762
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
763
+ }
764
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
765
+ const decoder = new TextDecoder();
766
+ return decoder.decode(bytes);
767
+ }
768
+
769
+ /**
770
+ * PaginationManager handles the conversion between uniform cursor-based pagination
771
+ * and the specific pagination type for each service
772
+ */
773
+ class PaginationManager {
774
+ /**
775
+ * Create a pagination cursor for subsequent page requests
776
+ */
777
+ static createCursor({ pageInfo, type }) {
778
+ if (!pageInfo.hasMore) {
779
+ return undefined;
780
+ }
781
+ const cursorData = {
782
+ type,
783
+ pageSize: pageInfo.pageSize,
784
+ };
785
+ switch (type) {
786
+ case PaginationType.OFFSET:
787
+ if (pageInfo.currentPage) {
788
+ cursorData.pageNumber = pageInfo.currentPage + 1;
789
+ }
790
+ break;
791
+ case PaginationType.TOKEN:
792
+ if (pageInfo.continuationToken) {
793
+ cursorData.continuationToken = pageInfo.continuationToken;
794
+ }
795
+ else {
796
+ return undefined; // No continuation token, can't continue
797
+ }
798
+ break;
799
+ }
800
+ return {
801
+ value: encodeBase64(JSON.stringify(cursorData))
802
+ };
803
+ }
804
+ /**
805
+ * Create a paginated response with navigation cursors
806
+ */
807
+ static createPaginatedResponse({ pageInfo, type }, items) {
808
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
809
+ // Create previous page cursor if applicable
810
+ let previousCursor = undefined;
811
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
812
+ const prevCursorData = {
813
+ type,
814
+ pageNumber: pageInfo.currentPage - 1,
815
+ pageSize: pageInfo.pageSize,
816
+ };
817
+ previousCursor = {
818
+ value: encodeBase64(JSON.stringify(prevCursorData))
819
+ };
820
+ }
821
+ // Calculate total pages if we have totalCount and pageSize
822
+ let totalPages = undefined;
823
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
824
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
825
+ }
826
+ // Determine if this pagination type supports page jumping
827
+ const supportsPageJump = type === PaginationType.OFFSET;
828
+ // Create the result object with all fields, then filter out undefined values
829
+ const result = filterUndefined({
830
+ items,
831
+ totalCount: pageInfo.totalCount,
832
+ hasNextPage: pageInfo.hasMore,
833
+ nextCursor: nextCursor,
834
+ previousCursor: previousCursor,
835
+ currentPage: pageInfo.currentPage,
836
+ totalPages,
837
+ supportsPageJump
838
+ });
839
+ return result;
840
+ }
841
+ }
842
+
843
+ /**
844
+ * Creates headers object from key-value pairs
845
+ * @param headersObj - Object containing header key-value pairs
846
+ * @returns Headers object with all values converted to strings
847
+ *
848
+ * @example
849
+ * ```typescript
850
+ * // Single header
851
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
852
+ *
853
+ * // Multiple headers
854
+ * const headers = createHeaders({
855
+ * 'X-UIPATH-FolderKey': '1234567890',
856
+ * 'X-UIPATH-OrganizationUnitId': 123,
857
+ * 'Accept': 'application/json'
858
+ * });
859
+ *
860
+ * // Using constants
861
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
862
+ * const headers = createHeaders({
863
+ * [FOLDER_KEY]: 'abc-123',
864
+ * [FOLDER_ID]: 456
865
+ * });
866
+ *
867
+ * // Empty headers
868
+ * const headers = createHeaders();
869
+ * ```
870
+ */
871
+ function createHeaders(headersObj) {
872
+ const headers = {};
873
+ for (const [key, value] of Object.entries(headersObj)) {
874
+ if (value !== undefined && value !== null) {
875
+ headers[key] = value.toString();
876
+ }
877
+ }
878
+ return headers;
879
+ }
880
+
881
+ /**
882
+ * Common constants used across the SDK
883
+ */
884
+ /**
885
+ * Prefix used for OData query parameters
886
+ */
887
+ const ODATA_PREFIX = '$';
888
+ /**
889
+ * HTTP methods
890
+ */
891
+ const HTTP_METHODS = {
892
+ GET: 'GET',
893
+ POST: 'POST'};
894
+ /**
895
+ * OData OFFSET pagination parameter names (ODATA-style)
896
+ */
897
+ const ODATA_OFFSET_PARAMS = {
898
+ /** OData page size parameter name */
899
+ PAGE_SIZE_PARAM: '$top',
900
+ /** OData offset parameter name */
901
+ OFFSET_PARAM: '$skip',
902
+ /** OData count parameter name */
903
+ COUNT_PARAM: '$count'
904
+ };
905
+ /**
906
+ * Bucket TOKEN pagination parameter names
907
+ */
908
+ const BUCKET_TOKEN_PARAMS = {
909
+ /** Bucket page size parameter name */
910
+ PAGE_SIZE_PARAM: 'takeHint',
911
+ /** Bucket token parameter name */
912
+ TOKEN_PARAM: 'continuationToken'
913
+ };
914
+
915
+ /**
916
+ * Converts a UTC timestamp string (e.g., "5/8/2026 11:20:17 AM") to ISO 8601 UTC format.
917
+ * Returns the original value if parsing fails.
918
+ */
919
+ /**
920
+ * Converts a string from PascalCase to camelCase
921
+ * @param str The PascalCase string to convert
922
+ * @returns The camelCase version of the string
923
+ *
924
+ * @example
925
+ * ```typescript
926
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
927
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
928
+ * ```
929
+ */
930
+ function pascalToCamelCase(str) {
931
+ if (!str)
932
+ return str;
933
+ return str.charAt(0).toLowerCase() + str.slice(1);
934
+ }
935
+ /**
936
+ * Generic function to transform object keys using a provided case conversion function
937
+ * @param data The object to transform
938
+ * @param convertCase The function to convert each key
939
+ * @returns A new object with transformed keys
940
+ */
941
+ function transformCaseKeys(data, convertCase) {
942
+ // Handle array of objects
943
+ if (Array.isArray(data)) {
944
+ return data.map(item => {
945
+ // If the array element is a primitive (string, number, etc.), return it as is
946
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
947
+ return item;
948
+ }
949
+ // Only recursively transform if it's actually an object
950
+ return transformCaseKeys(item, convertCase);
951
+ });
952
+ }
953
+ const result = {};
954
+ for (const [key, value] of Object.entries(data)) {
955
+ const transformedKey = convertCase(key);
956
+ // Recursively transform nested objects and arrays
957
+ if (value !== null && typeof value === 'object') {
958
+ result[transformedKey] = transformCaseKeys(value, convertCase);
959
+ }
960
+ else {
961
+ result[transformedKey] = value;
962
+ }
963
+ }
964
+ return result;
965
+ }
966
+ /**
967
+ * Transforms an object's keys from PascalCase to camelCase
968
+ * @param data The object with PascalCase keys
969
+ * @returns A new object with all keys converted to camelCase
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * // Simple object
974
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
975
+ * // Result: { id: "123", taskName: "Invoice" }
976
+ *
977
+ * // Nested object
978
+ * pascalToCamelCaseKeys({
979
+ * TaskId: "456",
980
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
981
+ * });
982
+ * // Result: {
983
+ * // taskId: "456",
984
+ * // taskDetails: { assignedUser: "John", priority: "High" }
985
+ * // }
986
+ *
987
+ * // Array of objects
988
+ * pascalToCamelCaseKeys([
989
+ * { Id: "1", IsComplete: false },
990
+ * { Id: "2", IsComplete: true }
991
+ * ]);
992
+ * // Result: [
993
+ * // { id: "1", isComplete: false },
994
+ * // { id: "2", isComplete: true }
995
+ * // ]
996
+ * ```
997
+ */
998
+ function pascalToCamelCaseKeys(data) {
999
+ return transformCaseKeys(data, pascalToCamelCase);
1000
+ }
1001
+ /**
1002
+ * Adds a prefix to specified keys in an object, returning a new object.
1003
+ * Only the provided keys are prefixed; all others are left unchanged.
1004
+ *
1005
+ * @param obj The source object
1006
+ * @param prefix The prefix to add (e.g., '$')
1007
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1008
+ * @returns A new object with specified keys prefixed
1009
+ *
1010
+ * @example
1011
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1012
+ */
1013
+ function addPrefixToKeys(obj, prefix, keys) {
1014
+ const result = {};
1015
+ for (const [key, value] of Object.entries(obj)) {
1016
+ if (keys.includes(key)) {
1017
+ result[`${prefix}${key}`] = value;
1018
+ }
1019
+ else {
1020
+ result[key] = value;
1021
+ }
1022
+ }
1023
+ return result;
1024
+ }
1025
+
1026
+ /**
1027
+ * Constants used throughout the pagination system
1028
+ */
1029
+ /** Maximum number of items that can be requested in a single page */
1030
+ const MAX_PAGE_SIZE = 1000;
1031
+ /** Default page size when jumpToPage is used without specifying pageSize */
1032
+ const DEFAULT_PAGE_SIZE = 50;
1033
+ /** Default field name for items in a paginated response */
1034
+ const DEFAULT_ITEMS_FIELD = 'value';
1035
+ /** Default field name for total count in a paginated response */
1036
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1037
+ /**
1038
+ * Limits the page size to the maximum allowed value
1039
+ * @param pageSize - Requested page size
1040
+ * @returns Limited page size value
1041
+ */
1042
+ function getLimitedPageSize(pageSize) {
1043
+ if (pageSize === undefined || pageSize === null) {
1044
+ return DEFAULT_PAGE_SIZE;
1045
+ }
1046
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1047
+ }
1048
+
1049
+ /**
1050
+ * Helper functions for pagination that can be used across services
1051
+ */
1052
+ class PaginationHelpers {
1053
+ /**
1054
+ * Checks if any pagination parameters are provided
1055
+ *
1056
+ * @param options - The options object to check
1057
+ * @returns True if any pagination parameter is defined, false otherwise
1058
+ */
1059
+ static hasPaginationParameters(options = {}) {
1060
+ const { cursor, pageSize, jumpToPage } = options;
1061
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1062
+ }
1063
+ /**
1064
+ * Parse a pagination cursor string into cursor data
1065
+ */
1066
+ static parseCursor(cursorString) {
1067
+ try {
1068
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1069
+ return cursorData;
1070
+ }
1071
+ catch {
1072
+ throw new Error('Invalid pagination cursor');
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Validates cursor format and structure
1077
+ *
1078
+ * @param paginationOptions - The pagination options containing the cursor
1079
+ * @param paginationType - Optional pagination type to validate against
1080
+ */
1081
+ static validateCursor(paginationOptions, paginationType) {
1082
+ if (paginationOptions.cursor !== undefined) {
1083
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1084
+ throw new Error('cursor must contain a valid cursor string');
1085
+ }
1086
+ try {
1087
+ // Try to parse the cursor to validate it
1088
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1089
+ // If type is provided, validate cursor contains expected type information
1090
+ if (paginationType) {
1091
+ if (!cursorData.type) {
1092
+ throw new Error('Invalid cursor: missing pagination type');
1093
+ }
1094
+ // Check pagination type compatibility
1095
+ if (cursorData.type !== paginationType) {
1096
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1097
+ }
1098
+ }
1099
+ }
1100
+ catch (error) {
1101
+ if (error instanceof Error) {
1102
+ // If it's already our error with specific message, pass it through
1103
+ if (error.message.startsWith('Invalid cursor') ||
1104
+ error.message.startsWith('Pagination type mismatch')) {
1105
+ throw error;
1106
+ }
1107
+ }
1108
+ throw new Error('Invalid pagination cursor format');
1109
+ }
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Comprehensive validation for pagination options
1114
+ *
1115
+ * @param options - The pagination options to validate
1116
+ * @param paginationType - The pagination type these options will be used with
1117
+ * @returns Processed pagination parameters ready for use
1118
+ */
1119
+ static validatePaginationOptions(options, paginationType) {
1120
+ // Validate pageSize
1121
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1122
+ throw new Error('pageSize must be a positive number');
1123
+ }
1124
+ // Validate jumpToPage
1125
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1126
+ throw new Error('jumpToPage must be a positive number');
1127
+ }
1128
+ // Validate cursor
1129
+ PaginationHelpers.validateCursor(options, paginationType);
1130
+ // Validate service compatibility
1131
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1132
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1133
+ }
1134
+ // Get processed parameters
1135
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1136
+ }
1137
+ /**
1138
+ * Convert a unified pagination options to service-specific parameters
1139
+ */
1140
+ static getRequestParameters(options, paginationType) {
1141
+ // Handle jumpToPage
1142
+ if (options.jumpToPage !== undefined) {
1143
+ const jumpToPageOptions = {
1144
+ pageSize: options.pageSize,
1145
+ pageNumber: options.jumpToPage
1146
+ };
1147
+ return filterUndefined(jumpToPageOptions);
1148
+ }
1149
+ // If no cursor is provided, it's a first page request
1150
+ if (!options.cursor) {
1151
+ const firstPageOptions = {
1152
+ pageSize: options.pageSize,
1153
+ // Only set pageNumber for OFFSET pagination
1154
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1155
+ };
1156
+ return filterUndefined(firstPageOptions);
1157
+ }
1158
+ // Parse the cursor
1159
+ try {
1160
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1161
+ const cursorBasedOptions = {
1162
+ pageSize: cursorData.pageSize || options.pageSize,
1163
+ pageNumber: cursorData.pageNumber,
1164
+ continuationToken: cursorData.continuationToken,
1165
+ type: cursorData.type,
1166
+ };
1167
+ return filterUndefined(cursorBasedOptions);
1168
+ }
1169
+ catch {
1170
+ throw new Error('Invalid pagination cursor');
1171
+ }
1172
+ }
1173
+ /**
1174
+ * Helper method for paginated resource retrieval
1175
+ *
1176
+ * @param params - Parameters for pagination
1177
+ * @returns Promise resolving to a paginated result
1178
+ */
1179
+ static async getAllPaginated(params) {
1180
+ const { serviceAccess, getEndpoint, folderId, headers: providedHeaders, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1181
+ const endpoint = getEndpoint(folderId);
1182
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1183
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1184
+ headers,
1185
+ params: additionalParams,
1186
+ pagination: {
1187
+ paginationType: options.paginationType || PaginationType.OFFSET,
1188
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1189
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1190
+ continuationTokenField: options.continuationTokenField,
1191
+ paginationParams: options.paginationParams
1192
+ }
1193
+ });
1194
+ // Parse items - automatically handle JSON string responses
1195
+ const rawItems = paginatedResponse.items;
1196
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1197
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1198
+ return {
1199
+ ...paginatedResponse,
1200
+ items: transformedItems
1201
+ };
1202
+ }
1203
+ /**
1204
+ * Helper method for non-paginated resource retrieval
1205
+ *
1206
+ * @param params - Parameters for non-paginated resource retrieval
1207
+ * @returns Promise resolving to an object with data and totalCount
1208
+ */
1209
+ static async getAllNonPaginated(params) {
1210
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, headers: providedHeaders, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1211
+ // Set default field names
1212
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1213
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1214
+ // Determine endpoint and headers based on folderId
1215
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1216
+ const headers = providedHeaders ?? (folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {});
1217
+ // Make the API call based on method
1218
+ let response;
1219
+ if (method === HTTP_METHODS.POST) {
1220
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1221
+ }
1222
+ else {
1223
+ response = await serviceAccess.get(endpoint, {
1224
+ params: additionalParams,
1225
+ headers
1226
+ });
1227
+ }
1228
+ // Extract and transform items from response
1229
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1230
+ const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
1231
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1232
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1233
+ // Parse items - automatically handle JSON string responses
1234
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1235
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1236
+ return {
1237
+ items,
1238
+ totalCount
1239
+ };
1240
+ }
1241
+ /**
1242
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1243
+ *
1244
+ * @param config - Configuration for the getAll operation
1245
+ * @param options - Request options including pagination parameters
1246
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1247
+ */
1248
+ static async getAll(config, options) {
1249
+ const optionsWithDefaults = options || {};
1250
+ const { folderId, pageSize, cursor, jumpToPage, ...restOptions } = optionsWithDefaults;
1251
+ // Determine if pagination is requested
1252
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1253
+ // Process parameters (custom processing if provided, otherwise default)
1254
+ let processedOptions = restOptions;
1255
+ if (config.processParametersFn) {
1256
+ processedOptions = config.processParametersFn(restOptions, folderId);
1257
+ }
1258
+ // Apply ODATA prefix to keys (excluding specified keys)
1259
+ const excludeKeys = config.excludeFromPrefix || [];
1260
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1261
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1262
+ // Default pagination options
1263
+ const paginationOptions = {
1264
+ paginationType: PaginationType.OFFSET,
1265
+ itemsField: DEFAULT_ITEMS_FIELD,
1266
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1267
+ ...config.pagination
1268
+ };
1269
+ // Paginated flow
1270
+ if (isPaginationRequested) {
1271
+ return PaginationHelpers.getAllPaginated({
1272
+ serviceAccess: config.serviceAccess,
1273
+ getEndpoint: config.getEndpoint,
1274
+ folderId,
1275
+ headers: config.headers,
1276
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1277
+ additionalParams: prefixedOptions,
1278
+ transformFn: config.transformFn,
1279
+ method: config.method,
1280
+ options: {
1281
+ ...paginationOptions,
1282
+ paginationParams: config.pagination?.paginationParams
1283
+ }
1284
+ }); // Type assertion needed due to conditional return
1285
+ }
1286
+ // Non-paginated flow
1287
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1288
+ return PaginationHelpers.getAllNonPaginated({
1289
+ serviceAccess: config.serviceAccess,
1290
+ getAllEndpoint: config.getEndpoint(),
1291
+ getByFolderEndpoint: byFolderEndpoint,
1292
+ folderId,
1293
+ headers: config.headers,
1294
+ additionalParams: prefixedOptions,
1295
+ transformFn: config.transformFn,
1296
+ method: config.method,
1297
+ options: {
1298
+ itemsField: paginationOptions.itemsField,
1299
+ totalCountField: paginationOptions.totalCountField
1300
+ }
1301
+ });
1302
+ }
1303
+ }
1304
+
1305
+ /**
1306
+ * SDK Internals Registry - Internal registry for SDK instances
1307
+ *
1308
+ * This class is NOT exported in the public API.
1309
+ * It provides a secure way to share SDK internals between
1310
+ * the UiPath class and service classes without exposing them publicly.
1311
+ *
1312
+ * @internal
1313
+ */
1314
+ // Global symbol key to ensure WeakMap is shared across module instances
1315
+ // This prevents issues when core and service modules are bundled separately
1316
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1317
+ // Get or create the global WeakMap store
1318
+ const getGlobalStore = () => {
1319
+ const globalObj = globalThis;
1320
+ if (!globalObj[REGISTRY_KEY]) {
1321
+ globalObj[REGISTRY_KEY] = new WeakMap();
1322
+ }
1323
+ return globalObj[REGISTRY_KEY];
1324
+ };
1325
+ /**
1326
+ * Internal registry for SDK private components.
1327
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1328
+ * garbage collected when the SDK instance is no longer referenced.
1329
+ *
1330
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1331
+ * across separately bundled modules (core, entities, tasks, etc.).
1332
+ *
1333
+ * @internal - Not exported in public API
1334
+ */
1335
+ class SDKInternalsRegistry {
1336
+ // Use global store to ensure sharing across module bundles
1337
+ static get store() {
1338
+ return getGlobalStore();
1339
+ }
1340
+ /**
1341
+ * Register SDK instance internals
1342
+ * Called by UiPath constructor
1343
+ */
1344
+ static set(instance, internals) {
1345
+ this.store.set(instance, internals);
1346
+ }
1347
+ /**
1348
+ * Retrieve SDK instance internals
1349
+ * Called by BaseService constructor
1350
+ */
1351
+ static get(instance) {
1352
+ const internals = this.store.get(instance);
1353
+ if (!internals) {
1354
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1355
+ }
1356
+ return internals;
1357
+ }
1358
+ }
1359
+
1360
+ var _BaseService_apiClient;
1361
+ /**
1362
+ * Base class for all UiPath SDK services.
1363
+ *
1364
+ * Provides common functionality for authentication, configuration, and API communication.
1365
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1366
+ *
1367
+ * This class implements the dependency injection pattern where services receive a configured
1368
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1369
+ * including authentication token management.
1370
+ *
1371
+ * @remarks
1372
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1373
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1374
+ *
1375
+ */
1376
+ class BaseService {
1377
+ /**
1378
+ * Creates a base service instance with dependency injection.
1379
+ *
1380
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1381
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1382
+ * and token management internally.
1383
+ *
1384
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1385
+ * Services receive this via dependency injection in the modular pattern.
1386
+ * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for
1387
+ * CAS external-app auth)
1388
+ *
1389
+ * @example
1390
+ * ```typescript
1391
+ * // Services automatically call this via super()
1392
+ * export class EntityService extends BaseService {
1393
+ * constructor(instance: IUiPath) {
1394
+ * super(instance); // Initializes the internal ApiClient
1395
+ * }
1396
+ * }
1397
+ *
1398
+ * // Usage in modular pattern
1399
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1400
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1401
+ *
1402
+ * const sdk = new UiPath(config);
1403
+ * await sdk.initialize();
1404
+ * const entities = new Entities(sdk);
1405
+ * ```
1406
+ */
1407
+ constructor(instance, headers) {
1408
+ // Private field - not visible via Object.keys() or any reflection
1409
+ _BaseService_apiClient.set(this, void 0);
1410
+ const { config, context, tokenManager, folderKey } = SDKInternalsRegistry.get(instance);
1411
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager, headers ? { headers } : {}), "f");
1412
+ this.config = { folderKey };
1413
+ }
1414
+ /**
1415
+ * Gets a valid authentication token, refreshing if necessary.
1416
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1417
+ *
1418
+ * @returns Promise resolving to a valid access token string
1419
+ * @throws AuthenticationError if no token is available or refresh fails
1420
+ */
1421
+ async getValidAuthToken() {
1422
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1423
+ }
1424
+ /**
1425
+ * Creates a service accessor for pagination helpers
1426
+ * This allows pagination helpers to access protected methods without making them public
1427
+ */
1428
+ createPaginationServiceAccess() {
1429
+ return {
1430
+ get: (path, options) => this.get(path, options || {}),
1431
+ post: (path, body, options) => this.post(path, body, options || {}),
1432
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1433
+ };
1434
+ }
1435
+ async request(method, path, options = {}) {
1436
+ switch (method.toUpperCase()) {
1437
+ case 'GET':
1438
+ return this.get(path, options);
1439
+ case 'POST':
1440
+ return this.post(path, options.body, options);
1441
+ case 'PUT':
1442
+ return this.put(path, options.body, options);
1443
+ case 'PATCH':
1444
+ return this.patch(path, options.body, options);
1445
+ case 'DELETE':
1446
+ return this.delete(path, options);
1447
+ default:
1448
+ throw new Error(`Unsupported HTTP method: ${method}`);
1449
+ }
1450
+ }
1451
+ async requestWithSpec(spec) {
1452
+ if (!spec.method || !spec.url) {
1453
+ throw new Error('Request spec must include method and url');
1454
+ }
1455
+ return this.request(spec.method, spec.url, spec);
1456
+ }
1457
+ async get(path, options = {}) {
1458
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1459
+ return { data: response };
1460
+ }
1461
+ async post(path, data, options = {}) {
1462
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1463
+ return { data: response };
1464
+ }
1465
+ async put(path, data, options = {}) {
1466
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1467
+ return { data: response };
1468
+ }
1469
+ async patch(path, data, options = {}) {
1470
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1471
+ return { data: response };
1472
+ }
1473
+ async delete(path, options = {}) {
1474
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1475
+ return { data: response };
1476
+ }
1477
+ /**
1478
+ * Execute a request with cursor-based pagination
1479
+ */
1480
+ async requestWithPagination(method, path, paginationOptions, options) {
1481
+ const paginationType = options.pagination.paginationType;
1482
+ // Validate and prepare pagination parameters
1483
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1484
+ // Prepare request parameters based on pagination type
1485
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1486
+ // For POST requests, merge pagination params into body and set params to undefined; for GET, use query params
1487
+ if (method.toUpperCase() === 'POST') {
1488
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1489
+ options.body = {
1490
+ ...existingBody,
1491
+ ...options.params,
1492
+ ...requestParams
1493
+ };
1494
+ options.params = undefined;
1495
+ }
1496
+ else {
1497
+ // Merge pagination parameters with existing parameters
1498
+ options.params = {
1499
+ ...options.params,
1500
+ ...requestParams
1501
+ };
1502
+ }
1503
+ // Make the request
1504
+ const response = await this.request(method, path, options);
1505
+ // Extract data from the response and create page result
1506
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1507
+ itemsField: options.pagination.itemsField,
1508
+ totalCountField: options.pagination.totalCountField,
1509
+ continuationTokenField: options.pagination.continuationTokenField
1510
+ });
1511
+ }
1512
+ /**
1513
+ * Validates and prepares pagination parameters from options
1514
+ */
1515
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1516
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1517
+ }
1518
+ /**
1519
+ * Prepares request parameters for pagination based on pagination type
1520
+ */
1521
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1522
+ const requestParams = {};
1523
+ let limitedPageSize;
1524
+ const paginationParams = paginationConfig?.paginationParams;
1525
+ switch (paginationType) {
1526
+ case PaginationType.OFFSET:
1527
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1528
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1529
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1530
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1531
+ // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
1532
+ // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
1533
+ const convertToSkip = paginationParams?.convertToSkip ?? true;
1534
+ requestParams[pageSizeParam] = limitedPageSize;
1535
+ if (convertToSkip) {
1536
+ if (params.pageNumber && params.pageNumber > 1) {
1537
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1538
+ }
1539
+ }
1540
+ else {
1541
+ requestParams[offsetParam] = params.pageNumber || 1;
1542
+ }
1543
+ {
1544
+ requestParams[countParam] = true;
1545
+ }
1546
+ break;
1547
+ case PaginationType.TOKEN:
1548
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1549
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1550
+ if (params.pageSize) {
1551
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1552
+ }
1553
+ if (params.continuationToken) {
1554
+ requestParams[tokenParam] = params.continuationToken;
1555
+ }
1556
+ break;
1557
+ }
1558
+ return requestParams;
1559
+ }
1560
+ /**
1561
+ * Creates a paginated response from API response
1562
+ */
1563
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1564
+ // Extract fields from response
1565
+ const itemsField = fields.itemsField ||
1566
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1567
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1568
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1569
+ // Extract items and metadata
1570
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
1571
+ const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
1572
+ const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
1573
+ const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
1574
+ const continuationToken = response.data[continuationTokenField];
1575
+ // Determine if there are more pages
1576
+ const hasMore = this.determineHasMorePages(paginationType, {
1577
+ totalCount,
1578
+ pageSize: params.pageSize,
1579
+ currentPage: params.pageNumber || 1,
1580
+ itemsCount: items.length,
1581
+ continuationToken
1582
+ });
1583
+ // Create and return the page result
1584
+ return PaginationManager.createPaginatedResponse({
1585
+ pageInfo: {
1586
+ hasMore,
1587
+ totalCount,
1588
+ currentPage: params.pageNumber,
1589
+ pageSize: params.pageSize,
1590
+ continuationToken
1591
+ },
1592
+ type: paginationType,
1593
+ }, items);
1594
+ }
1595
+ /**
1596
+ * Determines if there are more pages based on pagination type and metadata
1597
+ */
1598
+ determineHasMorePages(paginationType, info) {
1599
+ switch (paginationType) {
1600
+ case PaginationType.OFFSET:
1601
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1602
+ // If totalCount is available, use it for precise calculation
1603
+ if (info.totalCount !== undefined) {
1604
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1605
+ }
1606
+ // Fallback when totalCount is not available
1607
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1608
+ return info.itemsCount === effectivePageSize;
1609
+ case PaginationType.TOKEN:
1610
+ return !!info.continuationToken;
1611
+ default:
1612
+ return false;
1613
+ }
1614
+ }
1615
+ }
1616
+ _BaseService_apiClient = new WeakMap();
1617
+
1618
+ /** Status of a span: whether it completed successfully, with an error, or was not set. */
1619
+ var SpanStatus;
1620
+ (function (SpanStatus) {
1621
+ SpanStatus["Unset"] = "Unset";
1622
+ SpanStatus["Ok"] = "Ok";
1623
+ SpanStatus["Error"] = "Error";
1624
+ /** Span is still in progress. */
1625
+ SpanStatus["Running"] = "Running";
1626
+ /** Span data is hidden from the caller due to tenant/folder permission rules. */
1627
+ SpanStatus["Restricted"] = "Restricted";
1628
+ /** Span was cancelled before completion. */
1629
+ SpanStatus["Cancelled"] = "Cancelled";
1630
+ })(SpanStatus || (SpanStatus = {}));
1631
+ /** Platform source that produced the span. */
1632
+ var SpanSource;
1633
+ (function (SpanSource) {
1634
+ SpanSource["Testing"] = "Testing";
1635
+ SpanSource["Agents"] = "Agents";
1636
+ SpanSource["ProcessOrchestration"] = "ProcessOrchestration";
1637
+ SpanSource["ApiWorkflows"] = "ApiWorkflows";
1638
+ SpanSource["Robots"] = "Robots";
1639
+ SpanSource["ConversationalAgentsService"] = "ConversationalAgentsService";
1640
+ SpanSource["IntegrationServiceTrigger"] = "IntegrationServiceTrigger";
1641
+ SpanSource["Playground"] = "Playground";
1642
+ SpanSource["Governance"] = "Governance";
1643
+ /** Intelligent Experience Platform — unstructured and complex document processing source. */
1644
+ SpanSource["IXPUnstructuredAndComplexDocuments"] = "IXPUnstructuredAndComplexDocuments";
1645
+ /** Agents authored in code (as opposed to visual/no-code designers). */
1646
+ SpanSource["CodedAgents"] = "CodedAgents";
1647
+ /** Intelligent Experience Platform — communications mining source. */
1648
+ SpanSource["IXPCommunicationsMining"] = "IXPCommunicationsMining";
1649
+ /** UiPath Context Grounding — span produced by the Enterprise Context Service for RAG/knowledge-base operations. */
1650
+ SpanSource["EnterpriseContextService"] = "EnterpriseContextService";
1651
+ /** Model Context Protocol — span produced by an MCP server integration. */
1652
+ SpanSource["MCP"] = "MCP";
1653
+ /** Agent-to-Agent — span produced by an A2A protocol call between agents. */
1654
+ SpanSource["A2A"] = "A2A";
1655
+ /** Serverless — span produced by a serverless function execution. */
1656
+ SpanSource["Serverless"] = "Serverless";
1657
+ })(SpanSource || (SpanSource = {}));
1658
+ /** Minimum severity level of events captured in the span. */
1659
+ var SpanVerbosityLevel;
1660
+ (function (SpanVerbosityLevel) {
1661
+ SpanVerbosityLevel["Verbose"] = "Verbose";
1662
+ SpanVerbosityLevel["Trace"] = "Trace";
1663
+ SpanVerbosityLevel["Information"] = "Information";
1664
+ SpanVerbosityLevel["Warning"] = "Warning";
1665
+ SpanVerbosityLevel["Error"] = "Error";
1666
+ SpanVerbosityLevel["Critical"] = "Critical";
1667
+ SpanVerbosityLevel["Off"] = "Off";
1668
+ })(SpanVerbosityLevel || (SpanVerbosityLevel = {}));
1669
+ /** Whether the span was produced during a debug or production runtime. */
1670
+ var SpanExecutionType;
1671
+ (function (SpanExecutionType) {
1672
+ SpanExecutionType["Debug"] = "Debug";
1673
+ SpanExecutionType["Runtime"] = "Runtime";
1674
+ })(SpanExecutionType || (SpanExecutionType = {}));
1675
+ /** Whether the caller has permission to read this span's data. */
1676
+ var SpanPermissionStatus;
1677
+ (function (SpanPermissionStatus) {
1678
+ SpanPermissionStatus["Allow"] = "Allow";
1679
+ /** Some span fields are redacted due to permission constraints (e.g. attributes visible but payload hidden). */
1680
+ SpanPermissionStatus["PartialBlock"] = "PartialBlock";
1681
+ SpanPermissionStatus["Block"] = "Block";
1682
+ })(SpanPermissionStatus || (SpanPermissionStatus = {}));
1683
+ /** Storage provider that created or manages the attachment. */
1684
+ var SpanAttachmentProvider;
1685
+ (function (SpanAttachmentProvider) {
1686
+ SpanAttachmentProvider["Orchestrator"] = "Orchestrator";
1687
+ /** Span attachment stored by the observability platform. */
1688
+ SpanAttachmentProvider["LLMOps"] = "LLMOps";
1689
+ })(SpanAttachmentProvider || (SpanAttachmentProvider = {}));
1690
+ /** Whether the attachment is an input, output, or neither. */
1691
+ var SpanAttachmentDirection;
1692
+ (function (SpanAttachmentDirection) {
1693
+ SpanAttachmentDirection["None"] = "None";
1694
+ SpanAttachmentDirection["In"] = "In";
1695
+ SpanAttachmentDirection["Out"] = "Out";
1696
+ })(SpanAttachmentDirection || (SpanAttachmentDirection = {}));
1697
+
1698
+ /** Maps integer Status values from the otel API to {@link SpanStatus} enum values. */
1699
+ const SpanStatusMap = {
1700
+ 0: SpanStatus.Unset,
1701
+ 1: SpanStatus.Ok,
1702
+ 2: SpanStatus.Error,
1703
+ 3: SpanStatus.Running,
1704
+ 4: SpanStatus.Restricted,
1705
+ 5: SpanStatus.Cancelled,
1706
+ };
1707
+ /** Maps integer Source values from the otel API to {@link SpanSource} enum values. */
1708
+ const SpanSourceMap = {
1709
+ 0: SpanSource.Testing,
1710
+ 1: SpanSource.Agents,
1711
+ 2: SpanSource.ProcessOrchestration,
1712
+ 3: SpanSource.ApiWorkflows,
1713
+ 4: SpanSource.Robots,
1714
+ 5: SpanSource.ConversationalAgentsService,
1715
+ 6: SpanSource.IntegrationServiceTrigger,
1716
+ 7: SpanSource.Playground,
1717
+ 8: SpanSource.Governance,
1718
+ 9: SpanSource.IXPUnstructuredAndComplexDocuments,
1719
+ 10: SpanSource.CodedAgents,
1720
+ 11: SpanSource.IXPCommunicationsMining,
1721
+ 12: SpanSource.EnterpriseContextService,
1722
+ 13: SpanSource.MCP,
1723
+ 14: SpanSource.A2A,
1724
+ 15: SpanSource.Serverless,
1725
+ };
1726
+ /** Maps integer VerbosityLevel values from the otel API to {@link SpanVerbosityLevel} enum values. */
1727
+ const SpanVerbosityLevelMap = {
1728
+ 0: SpanVerbosityLevel.Verbose,
1729
+ 1: SpanVerbosityLevel.Trace,
1730
+ 2: SpanVerbosityLevel.Information,
1731
+ 3: SpanVerbosityLevel.Warning,
1732
+ 4: SpanVerbosityLevel.Error,
1733
+ 5: SpanVerbosityLevel.Critical,
1734
+ 6: SpanVerbosityLevel.Off,
1735
+ };
1736
+ /** Maps integer ExecutionType values from the otel API to {@link SpanExecutionType} enum values. */
1737
+ const SpanExecutionTypeMap = {
1738
+ 0: SpanExecutionType.Debug,
1739
+ 1: SpanExecutionType.Runtime,
1740
+ };
1741
+ /** Maps integer PermissionStatus values from the otel API to {@link SpanPermissionStatus} enum values. */
1742
+ const SpanPermissionStatusMap = {
1743
+ 0: SpanPermissionStatus.Allow,
1744
+ 1: SpanPermissionStatus.PartialBlock,
1745
+ 2: SpanPermissionStatus.Block,
1746
+ };
1747
+ /** Maps integer Provider values from the otel API to {@link SpanAttachmentProvider} enum values. */
1748
+ const SpanAttachmentProviderMap = {
1749
+ 0: SpanAttachmentProvider.Orchestrator,
1750
+ 1: SpanAttachmentProvider.LLMOps,
1751
+ };
1752
+ /** Maps integer Direction values from the otel API to {@link SpanAttachmentDirection} enum values. */
1753
+ const SpanAttachmentDirectionMap = {
1754
+ 0: SpanAttachmentDirection.None,
1755
+ 1: SpanAttachmentDirection.In,
1756
+ 2: SpanAttachmentDirection.Out,
1757
+ };
1758
+
1759
+ /**
1760
+ * Base path constants for different services
1761
+ */
1762
+ const LLMOPS_BASE = 'llmopstenant_';
1763
+
1764
+ /**
1765
+ * Traces Service Endpoints
1766
+ */
1767
+ const TRACES_ENDPOINTS = {
1768
+ /** GET spans for a trace (OTEL format). Query params: traceId, pageSize, agentId, isHistorical */
1769
+ GET_BY_TRACE_ID: `${LLMOPS_BASE}/api/Traces/v2/spans/otel`,
1770
+ /** POST specific spans by ID. traceId in query via params, spanIds array in body */
1771
+ POST_BY_IDS: `${LLMOPS_BASE}/api/Traces/v2/spans/otel/byIds`,
1772
+ };
1773
+
1774
+ /**
1775
+ * SDK Telemetry constants.
1776
+ *
1777
+ * Only the SDK's identity (version, service name, role name, …) lives
1778
+ * here. The Application Insights connection string is injected into
1779
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
1780
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
1781
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
1782
+ * SDK's public API.
1783
+ */
1784
+ /** SDK version placeholder — patched by the SDK publish workflow. */
1785
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
1786
+
1787
+ /**
1788
+ * UiPath TypeScript SDK Telemetry
1789
+ *
1790
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
1791
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
1792
+ * does this independently, so events carry their own consumer's identity
1793
+ * and tenant context.
1794
+ */
1795
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
1796
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
1797
+ // from the `UiPath` constructor therefore wires up `@track` decorators
1798
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
1799
+ const sdkClient = getOrCreateClient(CLOUD_ROLE_NAME);
1800
+ const track = createTrack(sdkClient);
1801
+ createTrackEvent(sdkClient);
1802
+
1803
+ class TracesService extends BaseService {
1804
+ transformOtelSpan(raw) {
1805
+ const { Attributes, ExpiryTimeUtc, Attachments, ...rest } = raw;
1806
+ const base = pascalToCamelCaseKeys(rest);
1807
+ return {
1808
+ ...base,
1809
+ attributes: Attributes,
1810
+ expiredTime: ExpiryTimeUtc,
1811
+ status: SpanStatusMap[raw.Status] ?? SpanStatus.Unset,
1812
+ source: raw.Source == null ? null : (SpanSourceMap[raw.Source] ?? null),
1813
+ verbosityLevel: raw.VerbosityLevel == null ? null : (SpanVerbosityLevelMap[raw.VerbosityLevel] ?? null),
1814
+ executionType: raw.ExecutionType == null ? null : (SpanExecutionTypeMap[raw.ExecutionType] ?? null),
1815
+ permissionStatus: raw.PermissionStatus == null ? null : (SpanPermissionStatusMap[raw.PermissionStatus] ?? null),
1816
+ attachments: Attachments ? Attachments.map(a => ({
1817
+ provider: SpanAttachmentProviderMap[a.Provider] ?? SpanAttachmentProvider.Orchestrator,
1818
+ id: a.Id,
1819
+ fileName: a.FileName,
1820
+ mimeType: a.MimeType,
1821
+ direction: SpanAttachmentDirectionMap[a.Direction] ?? SpanAttachmentDirection.None,
1822
+ })) : null,
1823
+ };
1824
+ }
1825
+ /**
1826
+ * Gets all spans for a specific trace ID.
1827
+ *
1828
+ * Returns up to `pageSize` spans (default 1000) in a single fetch.
1829
+ * Accepts both GUID format and OTEL 32-char hex format — the API normalizes both.
1830
+ *
1831
+ * @param traceId - Trace identifier
1832
+ * @param options - Optional filters {@link TracesGetByIdOptions}
1833
+ * @returns Promise resolving to an array of {@link SpanGetResponse}, each containing span identity, timing, status, source platform, attributes, verbosity, execution type, lineage context, and any file attachments.
1834
+ * @example
1835
+ * ```typescript
1836
+ * import { Traces } from '@uipath/uipath-typescript/traces';
1837
+ *
1838
+ * const traces = new Traces(sdk);
1839
+ * const spans = await traces.getById('<traceId>');
1840
+ * console.log(spans.length, spans[0].spanType, spans[0].status);
1841
+ * ```
1842
+ * @example
1843
+ * ```typescript
1844
+ * // Filter to a specific agent's spans
1845
+ * const agentSpans = await traces.getById('<traceId>', {
1846
+ * agentId: '<agentId>',
1847
+ * pageSize: 500,
1848
+ * });
1849
+ * ```
1850
+ */
1851
+ async getById(traceId, options) {
1852
+ if (!traceId)
1853
+ throw new ValidationError({ message: 'traceId is required for getById' });
1854
+ const { pageSize = 1000, agentId, includeExpiredSpans } = options ?? {};
1855
+ const params = { traceId, pageSize };
1856
+ if (agentId !== undefined)
1857
+ params.agentId = agentId;
1858
+ if (includeExpiredSpans !== undefined)
1859
+ params.isHistorical = includeExpiredSpans;
1860
+ const response = await this.get(TRACES_ENDPOINTS.GET_BY_TRACE_ID, { params });
1861
+ const spans = response.data?.Spans ?? [];
1862
+ return spans.map(span => this.transformOtelSpan(span));
1863
+ }
1864
+ /**
1865
+ * Gets specific spans by trace ID and span IDs.
1866
+ *
1867
+ * Accepts OTEL 16-char hex or GUID format for span IDs.
1868
+ *
1869
+ * @param traceId - Trace identifier
1870
+ * @param spanIds - List of span IDs to retrieve
1871
+ * @returns Promise resolving to an array of matching {@link SpanGetResponse}
1872
+ * @example
1873
+ * ```typescript
1874
+ * import { Traces } from '@uipath/uipath-typescript/traces';
1875
+ *
1876
+ * const traces = new Traces(sdk);
1877
+ *
1878
+ * // First retrieve all spans to find the IDs you want
1879
+ * const allSpans = await traces.getById('<traceId>');
1880
+ * const spanIds = allSpans.slice(0, 3).map(s => s.id);
1881
+ *
1882
+ * const subset = await traces.getSpansByIds('<traceId>', spanIds);
1883
+ * ```
1884
+ */
1885
+ async getSpansByIds(traceId, spanIds) {
1886
+ if (!traceId)
1887
+ throw new ValidationError({ message: 'traceId is required for getSpansByIds' });
1888
+ const response = await this.post(TRACES_ENDPOINTS.POST_BY_IDS, spanIds, { params: { traceId } });
1889
+ const spans = response.data ?? [];
1890
+ return spans.map(span => this.transformOtelSpan(span));
1891
+ }
1892
+ }
1893
+ __decorate([
1894
+ track('Traces.GetById')
1895
+ ], TracesService.prototype, "getById", null);
1896
+ __decorate([
1897
+ track('Traces.GetSpansByIds')
1898
+ ], TracesService.prototype, "getSpansByIds", null);
1899
+
1900
+ export { SpanAttachmentDirection, SpanAttachmentProvider, SpanExecutionType, SpanPermissionStatus, SpanSource, SpanStatus, SpanVerbosityLevel, TracesService as Traces };