@uipath/uipath-typescript 1.3.10 → 1.4.0

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