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