@uipath/uipath-typescript 1.0.0-beta.17 → 1.0.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.
@@ -0,0 +1,2230 @@
1
+ import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+
20
+ function __decorate(decorators, target, key, desc) {
21
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
23
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+
27
+ function __classPrivateFieldGet(receiver, state, kind, f) {
28
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
29
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
30
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
31
+ }
32
+
33
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
34
+ if (kind === "m") throw new TypeError("Private method is not writable");
35
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
36
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
37
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
38
+ }
39
+
40
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
41
+ var e = new Error(message);
42
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
43
+ };
44
+
45
+ /**
46
+ * Base error class for all UiPath SDK errors
47
+ * Pure TypeScript class with clean interface
48
+ */
49
+ class UiPathError {
50
+ constructor(type, params) {
51
+ this.type = type;
52
+ this.message = params.message;
53
+ this.statusCode = params.statusCode;
54
+ this.requestId = params.requestId;
55
+ this.timestamp = new Date();
56
+ // Capture stack trace for debugging
57
+ this.stack = (new Error()).stack;
58
+ }
59
+ /**
60
+ * Returns a clean JSON representation of the error
61
+ */
62
+ toJSON() {
63
+ return {
64
+ type: this.type,
65
+ message: this.message,
66
+ statusCode: this.statusCode,
67
+ requestId: this.requestId,
68
+ timestamp: this.timestamp
69
+ };
70
+ }
71
+ /**
72
+ * Returns detailed debug information including stack trace
73
+ */
74
+ getDebugInfo() {
75
+ return {
76
+ ...this.toJSON(),
77
+ stack: this.stack
78
+ };
79
+ }
80
+ }
81
+
82
+ /**
83
+ * HTTP status code constants for error handling
84
+ */
85
+ const HttpStatus = {
86
+ // Client errors (4xx)
87
+ BAD_REQUEST: 400,
88
+ UNAUTHORIZED: 401,
89
+ FORBIDDEN: 403,
90
+ NOT_FOUND: 404,
91
+ TOO_MANY_REQUESTS: 429,
92
+ // Server errors (5xx)
93
+ INTERNAL_SERVER_ERROR: 500,
94
+ BAD_GATEWAY: 502,
95
+ SERVICE_UNAVAILABLE: 503,
96
+ GATEWAY_TIMEOUT: 504
97
+ };
98
+ /**
99
+ * Error type constants for consistent error identification
100
+ */
101
+ const ErrorType = {
102
+ AUTHENTICATION: 'AuthenticationError',
103
+ AUTHORIZATION: 'AuthorizationError',
104
+ VALIDATION: 'ValidationError',
105
+ NOT_FOUND: 'NotFoundError',
106
+ RATE_LIMIT: 'RateLimitError',
107
+ SERVER: 'ServerError',
108
+ NETWORK: 'NetworkError'
109
+ };
110
+ /**
111
+ * HTTP header constants for error handling
112
+ */
113
+ const HttpHeaders = {
114
+ X_REQUEST_ID: 'x-request-id'
115
+ };
116
+ /**
117
+ * Standard error message constants
118
+ */
119
+ const ErrorMessages = {
120
+ // Authentication errors
121
+ AUTHENTICATION_FAILED: 'Authentication failed',
122
+ // Authorization errors
123
+ ACCESS_DENIED: 'Access denied',
124
+ // Validation errors
125
+ VALIDATION_FAILED: 'Validation failed',
126
+ // Not found errors
127
+ RESOURCE_NOT_FOUND: 'Resource not found',
128
+ // Rate limit errors
129
+ RATE_LIMIT_EXCEEDED: 'Rate limit exceeded',
130
+ // Server errors
131
+ INTERNAL_SERVER_ERROR: 'Internal Server error occurred',
132
+ // Network errors
133
+ NETWORK_ERROR: 'Network error occurred',
134
+ REQUEST_TIMEOUT: 'Request timed out',
135
+ REQUEST_ABORTED: 'Request was aborted',
136
+ };
137
+ /**
138
+ * Error name constants for network error identification
139
+ */
140
+ const ErrorNames = {
141
+ ABORT_ERROR: 'AbortError'};
142
+
143
+ /**
144
+ * Error thrown when authentication fails (401 errors)
145
+ * Common scenarios:
146
+ * - Invalid credentials
147
+ * - Expired token
148
+ * - Missing authentication
149
+ */
150
+ class AuthenticationError extends UiPathError {
151
+ constructor(params = {}) {
152
+ super(ErrorType.AUTHENTICATION, {
153
+ message: params.message || ErrorMessages.AUTHENTICATION_FAILED,
154
+ statusCode: params.statusCode ?? HttpStatus.UNAUTHORIZED,
155
+ requestId: params.requestId
156
+ });
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Error thrown when authorization fails (403 errors)
162
+ * Common scenarios:
163
+ * - Insufficient permissions
164
+ * - Access denied to resource
165
+ * - Invalid scope
166
+ */
167
+ class AuthorizationError extends UiPathError {
168
+ constructor(params = {}) {
169
+ super(ErrorType.AUTHORIZATION, {
170
+ message: params.message || ErrorMessages.ACCESS_DENIED,
171
+ statusCode: params.statusCode ?? HttpStatus.FORBIDDEN,
172
+ requestId: params.requestId
173
+ });
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Error thrown when validation fails (400 errors or client-side validation)
179
+ * Common scenarios:
180
+ * - Invalid input parameters
181
+ * - Missing required fields
182
+ * - Invalid data format
183
+ */
184
+ class ValidationError extends UiPathError {
185
+ constructor(params = {}) {
186
+ super(ErrorType.VALIDATION, {
187
+ message: params.message || ErrorMessages.VALIDATION_FAILED,
188
+ statusCode: params.statusCode ?? HttpStatus.BAD_REQUEST,
189
+ requestId: params.requestId
190
+ });
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Error thrown when a resource is not found (404 errors)
196
+ * Common scenarios:
197
+ * - Resource doesn't exist
198
+ * - Invalid ID provided
199
+ * - Resource deleted
200
+ */
201
+ class NotFoundError extends UiPathError {
202
+ constructor(params = {}) {
203
+ super(ErrorType.NOT_FOUND, {
204
+ message: params.message || ErrorMessages.RESOURCE_NOT_FOUND,
205
+ statusCode: params.statusCode ?? HttpStatus.NOT_FOUND,
206
+ requestId: params.requestId
207
+ });
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Error thrown when rate limit is exceeded (429 errors)
213
+ * Common scenarios:
214
+ * - Too many requests in a time window
215
+ * - API throttling
216
+ */
217
+ class RateLimitError extends UiPathError {
218
+ constructor(params = {}) {
219
+ super(ErrorType.RATE_LIMIT, {
220
+ message: params.message || ErrorMessages.RATE_LIMIT_EXCEEDED,
221
+ statusCode: params.statusCode ?? HttpStatus.TOO_MANY_REQUESTS,
222
+ requestId: params.requestId
223
+ });
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Error thrown when server encounters an error (5xx errors)
229
+ * Common scenarios:
230
+ * - Internal server error
231
+ * - Service unavailable
232
+ * - Gateway timeout
233
+ */
234
+ class ServerError extends UiPathError {
235
+ constructor(params = {}) {
236
+ super(ErrorType.SERVER, {
237
+ message: params.message || ErrorMessages.INTERNAL_SERVER_ERROR,
238
+ statusCode: params.statusCode ?? HttpStatus.INTERNAL_SERVER_ERROR,
239
+ requestId: params.requestId
240
+ });
241
+ }
242
+ /**
243
+ * Checks if this is a temporary error that might succeed on retry
244
+ */
245
+ get isRetryable() {
246
+ return this.statusCode === HttpStatus.BAD_GATEWAY ||
247
+ this.statusCode === HttpStatus.SERVICE_UNAVAILABLE ||
248
+ this.statusCode === HttpStatus.GATEWAY_TIMEOUT;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Error thrown when network/connection issues occur
254
+ * Common scenarios:
255
+ * - Connection timeout
256
+ * - DNS resolution failure
257
+ * - Network unreachable
258
+ * - Request aborted
259
+ */
260
+ class NetworkError extends UiPathError {
261
+ constructor(params = {}) {
262
+ super(ErrorType.NETWORK, {
263
+ message: params.message || ErrorMessages.NETWORK_ERROR,
264
+ statusCode: params.statusCode, // Network errors typically don't have HTTP status codes
265
+ requestId: params.requestId
266
+ });
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Type guards for error response types
272
+ */
273
+ function isOrchestratorError(error) {
274
+ return typeof error === 'object' &&
275
+ error !== null &&
276
+ 'message' in error &&
277
+ 'errorCode' in error &&
278
+ typeof error.message === 'string' &&
279
+ typeof error.errorCode === 'number';
280
+ }
281
+ function isEntityError(error) {
282
+ return typeof error === 'object' &&
283
+ error !== null &&
284
+ 'error' in error &&
285
+ typeof error.error === 'string';
286
+ }
287
+ function isPimsError(error) {
288
+ return typeof error === 'object' &&
289
+ error !== null &&
290
+ 'type' in error &&
291
+ 'title' in error &&
292
+ 'status' in error &&
293
+ typeof error.type === 'string' &&
294
+ typeof error.title === 'string' &&
295
+ typeof error.status === 'number';
296
+ }
297
+
298
+ /**
299
+ * Parser for Orchestrator/Task error format
300
+ */
301
+ class OrchestratorErrorParser {
302
+ canParse(errorBody) {
303
+ return isOrchestratorError(errorBody);
304
+ }
305
+ parse(errorBody, response) {
306
+ const error = errorBody;
307
+ return {
308
+ message: error.message,
309
+ code: response?.status?.toString(),
310
+ details: {
311
+ errorCode: error.errorCode,
312
+ traceId: error.traceId,
313
+ originalResponse: error
314
+ },
315
+ requestId: error.traceId
316
+ };
317
+ }
318
+ }
319
+ /**
320
+ * Parser for Entity (Data Fabric) error format
321
+ */
322
+ class EntityErrorParser {
323
+ canParse(errorBody) {
324
+ return isEntityError(errorBody);
325
+ }
326
+ parse(errorBody, response) {
327
+ const error = errorBody;
328
+ return {
329
+ message: error.error,
330
+ code: response?.status?.toString(),
331
+ details: {
332
+ error: error.error,
333
+ traceId: error.traceId,
334
+ originalResponse: error
335
+ },
336
+ requestId: error.traceId
337
+ };
338
+ }
339
+ }
340
+ /**
341
+ * Parser for PIMS error format
342
+ */
343
+ class PimsErrorParser {
344
+ canParse(errorBody) {
345
+ return isPimsError(errorBody);
346
+ }
347
+ parse(errorBody, response) {
348
+ const error = errorBody;
349
+ let message = error.title;
350
+ // If there are validation errors, append them to the message for better visibility
351
+ if (error.errors && Object.keys(error.errors).length > 0) {
352
+ const errorMessages = Object.entries(error.errors)
353
+ .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
354
+ .join('; ');
355
+ message += `. Validation errors: ${errorMessages}`;
356
+ }
357
+ return {
358
+ message,
359
+ code: response?.status?.toString(),
360
+ details: {
361
+ type: error.type,
362
+ title: error.title,
363
+ status: error.status,
364
+ errors: error.errors,
365
+ traceId: error.traceId,
366
+ originalResponse: error
367
+ },
368
+ requestId: error.traceId
369
+ };
370
+ }
371
+ }
372
+ /**
373
+ * Fallback parser for unrecognized formats
374
+ */
375
+ class GenericErrorParser {
376
+ canParse(_errorBody) {
377
+ return true; // Always can parse as last resort
378
+ }
379
+ parse(errorBody, response) {
380
+ // For unknown error formats, just pass through the raw error with fallback message
381
+ const message = response?.statusText || 'An error occurred';
382
+ return {
383
+ message,
384
+ code: response?.status?.toString(),
385
+ details: {
386
+ originalResponse: errorBody
387
+ },
388
+ };
389
+ }
390
+ }
391
+ /**
392
+ * Main error response parser using Chain of Responsibility pattern
393
+ *
394
+ * This parser standardizes error responses from different UiPath services into a
395
+ * consistent format, regardless of the original error structure.
396
+ *
397
+ * Supported formats:
398
+ * 1. Orchestrator/Task: { message, errorCode, traceId }
399
+ * 2. Entity (Data Fabric): { error, traceId }
400
+ * 3. PIMS/Maestro: { type, title, status, errors?, traceId? }
401
+ * 4. Generic: Fallback for any other format
402
+ *
403
+ * @example
404
+ * const parser = new ErrorResponseParser();
405
+ * const errorInfo = await parser.parse(response);
406
+ * // errorInfo will have consistent structure regardless of service
407
+ */
408
+ class ErrorResponseParser {
409
+ constructor() {
410
+ this.strategies = [
411
+ new OrchestratorErrorParser(),
412
+ new EntityErrorParser(),
413
+ new PimsErrorParser(),
414
+ new GenericErrorParser() // Must be last
415
+ ];
416
+ }
417
+ /**
418
+ * Parses error response body into standardized format
419
+ * @param response - The HTTP response object
420
+ * @returns Standardized error information
421
+ */
422
+ async parse(response) {
423
+ try {
424
+ const errorBody = await response.json();
425
+ // Find the first strategy that can parse this error format
426
+ const strategy = this.strategies.find(s => s.canParse(errorBody));
427
+ // GenericErrorParser always returns true, so this will never be null
428
+ return strategy.parse(errorBody, response);
429
+ }
430
+ catch {
431
+ // Handle non-JSON responses
432
+ const responseText = await response.text().catch(() => '');
433
+ return {
434
+ message: response.statusText,
435
+ code: response.status.toString(),
436
+ details: {
437
+ parseError: 'Failed to parse error response as JSON',
438
+ responseText
439
+ },
440
+ requestId: response.headers.get(HttpHeaders.X_REQUEST_ID) || undefined
441
+ };
442
+ }
443
+ }
444
+ }
445
+ // Export singleton instance
446
+ const errorResponseParser = new ErrorResponseParser();
447
+
448
+ /**
449
+ * Factory for creating typed errors based on HTTP status codes
450
+ * Follows the Factory pattern for clean error instantiation
451
+ */
452
+ class ErrorFactory {
453
+ /**
454
+ * Creates appropriate error instance based on HTTP status code
455
+ */
456
+ static createFromHttpStatus(statusCode, errorInfo) {
457
+ const { message, requestId } = errorInfo;
458
+ // Map status codes to error types
459
+ switch (statusCode) {
460
+ case HttpStatus.BAD_REQUEST:
461
+ return new ValidationError({ message, statusCode, requestId });
462
+ case HttpStatus.UNAUTHORIZED:
463
+ return new AuthenticationError({ message, statusCode, requestId });
464
+ case HttpStatus.FORBIDDEN:
465
+ return new AuthorizationError({ message, statusCode, requestId });
466
+ case HttpStatus.NOT_FOUND:
467
+ return new NotFoundError({ message, statusCode, requestId });
468
+ case HttpStatus.TOO_MANY_REQUESTS:
469
+ return new RateLimitError({ message, statusCode, requestId });
470
+ default:
471
+ // For 5xx errors or any other status code
472
+ if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
473
+ return new ServerError({ message, statusCode, requestId });
474
+ }
475
+ // For unknown client errors, treat as validation error
476
+ return new ValidationError({
477
+ message: `${message} (HTTP ${statusCode})`,
478
+ statusCode,
479
+ requestId
480
+ });
481
+ }
482
+ }
483
+ /**
484
+ * Creates a NetworkError from a fetch/network error
485
+ */
486
+ static createNetworkError(error) {
487
+ let message = ErrorMessages.NETWORK_ERROR;
488
+ if (error instanceof Error) {
489
+ if (error.name === ErrorNames.ABORT_ERROR) {
490
+ message = ErrorMessages.REQUEST_ABORTED;
491
+ }
492
+ else if (error.message.includes('timeout')) {
493
+ message = ErrorMessages.REQUEST_TIMEOUT;
494
+ }
495
+ else {
496
+ message = error.message;
497
+ }
498
+ }
499
+ return new NetworkError({ message });
500
+ }
501
+ }
502
+
503
+ const FOLDER_ID = 'X-UIPATH-OrganizationUnitId';
504
+ /**
505
+ * Content type constants for HTTP requests/responses
506
+ */
507
+ const CONTENT_TYPES = {
508
+ JSON: 'application/json',
509
+ XML: 'application/xml',
510
+ OCTET_STREAM: 'application/octet-stream'
511
+ };
512
+ /**
513
+ * Response type constants for HTTP requests
514
+ */
515
+ const RESPONSE_TYPES = {
516
+ JSON: 'json',
517
+ TEXT: 'text',
518
+ BLOB: 'blob',
519
+ ARRAYBUFFER: 'arraybuffer'
520
+ };
521
+
522
+ class ApiClient {
523
+ constructor(config, executionContext, tokenManager, clientConfig = {}) {
524
+ this.defaultHeaders = {};
525
+ this.config = config;
526
+ this.executionContext = executionContext;
527
+ this.clientConfig = clientConfig;
528
+ this.tokenManager = tokenManager;
529
+ }
530
+ setDefaultHeaders(headers) {
531
+ this.defaultHeaders = { ...this.defaultHeaders, ...headers };
532
+ }
533
+ /**
534
+ * Gets a valid authentication token, refreshing if necessary.
535
+ * Used internally for API requests and exposed for services that need manual auth headers.
536
+ *
537
+ * @returns The valid token
538
+ * @throws AuthenticationError if no token available or refresh fails
539
+ */
540
+ async getValidToken() {
541
+ // Try to get token info from context
542
+ const tokenInfo = this.executionContext.get('tokenInfo');
543
+ if (!tokenInfo) {
544
+ throw new AuthenticationError({ message: 'No authentication token available. Make sure to initialize the SDK first.' });
545
+ }
546
+ // For secret-based tokens, they never expire
547
+ if (tokenInfo.type === 'secret') {
548
+ return tokenInfo.token;
549
+ }
550
+ // If token is not expired, return it
551
+ if (!this.tokenManager.isTokenExpired(tokenInfo)) {
552
+ return tokenInfo.token;
553
+ }
554
+ try {
555
+ const newToken = await this.tokenManager.refreshAccessToken();
556
+ return newToken.access_token;
557
+ }
558
+ catch (error) {
559
+ throw new AuthenticationError({
560
+ message: `Token refresh failed: ${error.message}. Please re-authenticate.`,
561
+ statusCode: HttpStatus.UNAUTHORIZED
562
+ });
563
+ }
564
+ }
565
+ async getDefaultHeaders() {
566
+ // Get headers from execution context first
567
+ const contextHeaders = this.executionContext.getHeaders();
568
+ // If Authorization header is already set in context, use that
569
+ if (contextHeaders['Authorization']) {
570
+ return {
571
+ ...contextHeaders,
572
+ 'Content-Type': CONTENT_TYPES.JSON,
573
+ ...this.defaultHeaders,
574
+ ...this.clientConfig.headers
575
+ };
576
+ }
577
+ const token = await this.getValidToken();
578
+ return {
579
+ ...contextHeaders,
580
+ 'Authorization': `Bearer ${token}`,
581
+ 'Content-Type': CONTENT_TYPES.JSON,
582
+ ...this.defaultHeaders,
583
+ ...this.clientConfig.headers
584
+ };
585
+ }
586
+ async request(method, path, options = {}) {
587
+ // Ensure path starts with a forward slash
588
+ const normalizedPath = path.startsWith('/') ? path.substring(1) : path;
589
+ // Construct URL with org and tenant names
590
+ const url = new URL(`${this.config.orgName}/${this.config.tenantName}/${normalizedPath}`, this.config.baseUrl).toString();
591
+ const headers = {
592
+ ...await this.getDefaultHeaders(),
593
+ ...options.headers
594
+ };
595
+ // Convert params to URLSearchParams
596
+ const searchParams = new URLSearchParams();
597
+ if (options.params) {
598
+ Object.entries(options.params).forEach(([key, value]) => {
599
+ searchParams.append(key, value.toString());
600
+ });
601
+ }
602
+ const fullUrl = searchParams.toString() ? `${url}?${searchParams.toString()}` : url;
603
+ try {
604
+ const response = await fetch(fullUrl, {
605
+ method,
606
+ headers,
607
+ body: options.body ? JSON.stringify(options.body) : undefined,
608
+ signal: options.signal
609
+ });
610
+ if (!response.ok) {
611
+ const errorInfo = await errorResponseParser.parse(response);
612
+ throw ErrorFactory.createFromHttpStatus(response.status, errorInfo);
613
+ }
614
+ if (response.status === 204) {
615
+ return undefined;
616
+ }
617
+ // Handle blob response type for binary data (e.g., file downloads)
618
+ if (options.responseType === RESPONSE_TYPES.BLOB) {
619
+ const blob = await response.blob();
620
+ return blob;
621
+ }
622
+ // Check if we're expecting XML
623
+ const acceptHeader = headers['Accept'] || headers['accept'];
624
+ if (acceptHeader === CONTENT_TYPES.XML) {
625
+ const text = await response.text();
626
+ return text;
627
+ }
628
+ return response.json();
629
+ }
630
+ catch (error) {
631
+ // If it's already one of our errors, re-throw it
632
+ if (error.type && error.type.includes('Error')) {
633
+ throw error;
634
+ }
635
+ // Otherwise, it's likely a network error
636
+ throw ErrorFactory.createNetworkError(error);
637
+ }
638
+ }
639
+ async get(path, options = {}) {
640
+ return this.request('GET', path, options);
641
+ }
642
+ async post(path, data, options = {}) {
643
+ return this.request('POST', path, { ...options, body: data });
644
+ }
645
+ async put(path, data, options = {}) {
646
+ return this.request('PUT', path, { ...options, body: data });
647
+ }
648
+ async patch(path, data, options = {}) {
649
+ return this.request('PATCH', path, { ...options, body: data });
650
+ }
651
+ async delete(path, options = {}) {
652
+ return this.request('DELETE', path, options);
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Pagination types supported by the SDK
658
+ */
659
+ var PaginationType;
660
+ (function (PaginationType) {
661
+ PaginationType["OFFSET"] = "offset";
662
+ PaginationType["TOKEN"] = "token";
663
+ })(PaginationType || (PaginationType = {}));
664
+
665
+ /**
666
+ * Collection of utility functions for working with objects
667
+ */
668
+ /**
669
+ * Filters out undefined values from an object
670
+ * @param obj The source object
671
+ * @returns A new object without undefined values
672
+ *
673
+ * @example
674
+ * ```typescript
675
+ * // Object with undefined values
676
+ * const options = {
677
+ * name: 'test',
678
+ * count: 5,
679
+ * prefix: undefined,
680
+ * suffix: null
681
+ * };
682
+ * const result = filterUndefined(options);
683
+ * // result = { name: 'test', count: 5, suffix: null }
684
+ * ```
685
+ */
686
+ function filterUndefined(obj) {
687
+ const result = {};
688
+ for (const [key, value] of Object.entries(obj)) {
689
+ if (value !== undefined) {
690
+ result[key] = value;
691
+ }
692
+ }
693
+ return result;
694
+ }
695
+
696
+ /**
697
+ * Utility functions for platform detection
698
+ */
699
+ /**
700
+ * Checks if code is running in a browser environment
701
+ */
702
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
703
+
704
+ /**
705
+ * Base64 encoding/decoding
706
+ */
707
+ /**
708
+ * Encodes a string to base64
709
+ * @param str - The string to encode
710
+ * @returns Base64 encoded string
711
+ */
712
+ function encodeBase64(str) {
713
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
714
+ const encoder = new TextEncoder();
715
+ const data = encoder.encode(str);
716
+ // Convert Uint8Array to base64
717
+ if (isBrowser) {
718
+ // Browser environment
719
+ // Convert Uint8Array to binary string then to base64
720
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
721
+ return btoa(binaryString);
722
+ }
723
+ else {
724
+ // Node.js environment
725
+ return Buffer.from(data).toString('base64');
726
+ }
727
+ }
728
+ /**
729
+ * Decodes a base64 string
730
+ * @param base64 - The base64 string to decode
731
+ * @returns Decoded string
732
+ */
733
+ function decodeBase64(base64) {
734
+ let bytes;
735
+ if (isBrowser) {
736
+ // Browser environment
737
+ const binaryString = atob(base64);
738
+ bytes = new Uint8Array(binaryString.length);
739
+ for (let i = 0; i < binaryString.length; i++) {
740
+ bytes[i] = binaryString.charCodeAt(i);
741
+ }
742
+ }
743
+ else {
744
+ // Node.js environment
745
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
746
+ }
747
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
748
+ const decoder = new TextDecoder();
749
+ return decoder.decode(bytes);
750
+ }
751
+
752
+ /**
753
+ * PaginationManager handles the conversion between uniform cursor-based pagination
754
+ * and the specific pagination type for each service
755
+ */
756
+ class PaginationManager {
757
+ /**
758
+ * Create a pagination cursor for subsequent page requests
759
+ */
760
+ static createCursor({ pageInfo, type }) {
761
+ if (!pageInfo.hasMore) {
762
+ return undefined;
763
+ }
764
+ const cursorData = {
765
+ type,
766
+ pageSize: pageInfo.pageSize,
767
+ };
768
+ switch (type) {
769
+ case PaginationType.OFFSET:
770
+ if (pageInfo.currentPage) {
771
+ cursorData.pageNumber = pageInfo.currentPage + 1;
772
+ }
773
+ break;
774
+ case PaginationType.TOKEN:
775
+ if (pageInfo.continuationToken) {
776
+ cursorData.continuationToken = pageInfo.continuationToken;
777
+ }
778
+ else {
779
+ return undefined; // No continuation token, can't continue
780
+ }
781
+ break;
782
+ }
783
+ return {
784
+ value: encodeBase64(JSON.stringify(cursorData))
785
+ };
786
+ }
787
+ /**
788
+ * Create a paginated response with navigation cursors
789
+ */
790
+ static createPaginatedResponse({ pageInfo, type }, items) {
791
+ const nextCursor = PaginationManager.createCursor({ pageInfo, type });
792
+ // Create previous page cursor if applicable
793
+ let previousCursor = undefined;
794
+ if (pageInfo.currentPage && pageInfo.currentPage > 1) {
795
+ const prevCursorData = {
796
+ type,
797
+ pageNumber: pageInfo.currentPage - 1,
798
+ pageSize: pageInfo.pageSize,
799
+ };
800
+ previousCursor = {
801
+ value: encodeBase64(JSON.stringify(prevCursorData))
802
+ };
803
+ }
804
+ // Calculate total pages if we have totalCount and pageSize
805
+ let totalPages = undefined;
806
+ if (pageInfo.totalCount !== undefined && pageInfo.pageSize) {
807
+ totalPages = Math.ceil(pageInfo.totalCount / pageInfo.pageSize);
808
+ }
809
+ // Determine if this pagination type supports page jumping
810
+ const supportsPageJump = type === PaginationType.OFFSET;
811
+ // Create the result object with all fields, then filter out undefined values
812
+ const result = filterUndefined({
813
+ items,
814
+ totalCount: pageInfo.totalCount,
815
+ hasNextPage: pageInfo.hasMore,
816
+ nextCursor: nextCursor,
817
+ previousCursor: previousCursor,
818
+ currentPage: pageInfo.currentPage,
819
+ totalPages,
820
+ supportsPageJump
821
+ });
822
+ return result;
823
+ }
824
+ }
825
+
826
+ /**
827
+ * Creates headers object from key-value pairs
828
+ * @param headersObj - Object containing header key-value pairs
829
+ * @returns Headers object with all values converted to strings
830
+ *
831
+ * @example
832
+ * ```typescript
833
+ * // Single header
834
+ * const headers = createHeaders({ 'X-UIPATH-FolderKey': '1234567890' });
835
+ *
836
+ * // Multiple headers
837
+ * const headers = createHeaders({
838
+ * 'X-UIPATH-FolderKey': '1234567890',
839
+ * 'X-UIPATH-OrganizationUnitId': 123,
840
+ * 'Accept': 'application/json'
841
+ * });
842
+ *
843
+ * // Using constants
844
+ * import { FOLDER_KEY, FOLDER_ID } from '../constants/headers';
845
+ * const headers = createHeaders({
846
+ * [FOLDER_KEY]: 'abc-123',
847
+ * [FOLDER_ID]: 456
848
+ * });
849
+ *
850
+ * // Empty headers
851
+ * const headers = createHeaders();
852
+ * ```
853
+ */
854
+ function createHeaders(headersObj) {
855
+ const headers = {};
856
+ for (const [key, value] of Object.entries(headersObj)) {
857
+ if (value !== undefined && value !== null) {
858
+ headers[key] = value.toString();
859
+ }
860
+ }
861
+ return headers;
862
+ }
863
+
864
+ /**
865
+ * Common constants used across the SDK
866
+ */
867
+ /**
868
+ * Prefix used for OData query parameters
869
+ */
870
+ const ODATA_PREFIX = '$';
871
+ /**
872
+ * HTTP methods
873
+ */
874
+ const HTTP_METHODS = {
875
+ GET: 'GET',
876
+ POST: 'POST'};
877
+ /**
878
+ * OData pagination constants
879
+ */
880
+ const ODATA_PAGINATION = {
881
+ /** Default field name for items in a paginated OData response */
882
+ ITEMS_FIELD: 'value',
883
+ /** Default field name for total count in a paginated OData response */
884
+ TOTAL_COUNT_FIELD: '@odata.count'
885
+ };
886
+ /**
887
+ * OData OFFSET pagination parameter names (ODATA-style)
888
+ */
889
+ const ODATA_OFFSET_PARAMS = {
890
+ /** OData page size parameter name */
891
+ PAGE_SIZE_PARAM: '$top',
892
+ /** OData offset parameter name */
893
+ OFFSET_PARAM: '$skip',
894
+ /** OData count parameter name */
895
+ COUNT_PARAM: '$count'
896
+ };
897
+ /**
898
+ * Bucket TOKEN pagination parameter names
899
+ */
900
+ const BUCKET_TOKEN_PARAMS = {
901
+ /** Bucket page size parameter name */
902
+ PAGE_SIZE_PARAM: 'takeHint',
903
+ /** Bucket token parameter name */
904
+ TOKEN_PARAM: 'continuationToken'
905
+ };
906
+
907
+ /**
908
+ * Transforms data by mapping fields according to the provided field mapping
909
+ * @param data The source data to transform
910
+ * @param fieldMapping Object mapping source field names to target field names
911
+ * @returns Transformed data with mapped field names
912
+ *
913
+ * @example
914
+ * ```typescript
915
+ * // Single object transformation
916
+ * const data = { id: '123', userName: 'john' };
917
+ * const mapping = { id: 'userId', userName: 'name' };
918
+ * const result = transformData(data, mapping);
919
+ * // result = { userId: '123', name: 'john' }
920
+ *
921
+ * // Array transformation
922
+ * const dataArray = [
923
+ * { id: '123', userName: 'john' },
924
+ * { id: '456', userName: 'jane' }
925
+ * ];
926
+ * const result = transformData(dataArray, mapping);
927
+ * // result = [
928
+ * // { userId: '123', name: 'john' },
929
+ * // { userId: '456', name: 'jane' }
930
+ * // ]
931
+ * ```
932
+ */
933
+ function transformData(data, fieldMapping) {
934
+ // Handle array of objects
935
+ if (Array.isArray(data)) {
936
+ return data.map(item => transformData(item, fieldMapping));
937
+ }
938
+ // Handle single object
939
+ const result = { ...data };
940
+ for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
941
+ if (sourceField in result) {
942
+ const value = result[sourceField];
943
+ delete result[sourceField];
944
+ result[targetField] = value;
945
+ }
946
+ }
947
+ return result;
948
+ }
949
+ /**
950
+ * Converts a string from PascalCase to camelCase
951
+ * @param str The PascalCase string to convert
952
+ * @returns The camelCase version of the string
953
+ *
954
+ * @example
955
+ * ```typescript
956
+ * pascalToCamelCase('HelloWorld'); // 'helloWorld'
957
+ * pascalToCamelCase('TaskAssignmentCriteria'); // 'taskAssignmentCriteria'
958
+ * ```
959
+ */
960
+ function pascalToCamelCase(str) {
961
+ if (!str)
962
+ return str;
963
+ return str.charAt(0).toLowerCase() + str.slice(1);
964
+ }
965
+ /**
966
+ * Generic function to transform object keys using a provided case conversion function
967
+ * @param data The object to transform
968
+ * @param convertCase The function to convert each key
969
+ * @returns A new object with transformed keys
970
+ */
971
+ function transformCaseKeys(data, convertCase) {
972
+ // Handle array of objects
973
+ if (Array.isArray(data)) {
974
+ return data.map(item => {
975
+ // If the array element is a primitive (string, number, etc.), return it as is
976
+ if (item === null || typeof item !== 'object' || typeof item === 'string') {
977
+ return item;
978
+ }
979
+ // Only recursively transform if it's actually an object
980
+ return transformCaseKeys(item, convertCase);
981
+ });
982
+ }
983
+ const result = {};
984
+ for (const [key, value] of Object.entries(data)) {
985
+ const transformedKey = convertCase(key);
986
+ // Recursively transform nested objects and arrays
987
+ if (value !== null && typeof value === 'object') {
988
+ result[transformedKey] = transformCaseKeys(value, convertCase);
989
+ }
990
+ else {
991
+ result[transformedKey] = value;
992
+ }
993
+ }
994
+ return result;
995
+ }
996
+ /**
997
+ * Transforms an object's keys from PascalCase to camelCase
998
+ * @param data The object with PascalCase keys
999
+ * @returns A new object with all keys converted to camelCase
1000
+ *
1001
+ * @example
1002
+ * ```typescript
1003
+ * // Simple object
1004
+ * pascalToCamelCaseKeys({ Id: "123", TaskName: "Invoice" });
1005
+ * // Result: { id: "123", taskName: "Invoice" }
1006
+ *
1007
+ * // Nested object
1008
+ * pascalToCamelCaseKeys({
1009
+ * TaskId: "456",
1010
+ * TaskDetails: { AssignedUser: "John", Priority: "High" }
1011
+ * });
1012
+ * // Result: {
1013
+ * // taskId: "456",
1014
+ * // taskDetails: { assignedUser: "John", priority: "High" }
1015
+ * // }
1016
+ *
1017
+ * // Array of objects
1018
+ * pascalToCamelCaseKeys([
1019
+ * { Id: "1", IsComplete: false },
1020
+ * { Id: "2", IsComplete: true }
1021
+ * ]);
1022
+ * // Result: [
1023
+ * // { id: "1", isComplete: false },
1024
+ * // { id: "2", isComplete: true }
1025
+ * // ]
1026
+ * ```
1027
+ */
1028
+ function pascalToCamelCaseKeys(data) {
1029
+ return transformCaseKeys(data, pascalToCamelCase);
1030
+ }
1031
+ /**
1032
+ * Adds a prefix to specified keys in an object, returning a new object.
1033
+ * Only the provided keys are prefixed; all others are left unchanged.
1034
+ *
1035
+ * @param obj The source object
1036
+ * @param prefix The prefix to add (e.g., '$')
1037
+ * @param keys The keys to prefix (e.g., ['expand', 'filter'])
1038
+ * @returns A new object with specified keys prefixed
1039
+ *
1040
+ * @example
1041
+ * addPrefixToKeys({ expand: 'a', foo: 1 }, '$', ['expand']) // { $expand: 'a', foo: 1 }
1042
+ */
1043
+ function addPrefixToKeys(obj, prefix, keys) {
1044
+ const result = {};
1045
+ for (const [key, value] of Object.entries(obj)) {
1046
+ if (keys.includes(key)) {
1047
+ result[`${prefix}${key}`] = value;
1048
+ }
1049
+ else {
1050
+ result[key] = value;
1051
+ }
1052
+ }
1053
+ return result;
1054
+ }
1055
+ /**
1056
+ * Creates a new map with the keys and values reversed
1057
+ * @param map The original map to reverse
1058
+ * @returns A new map with keys and values swapped
1059
+ *
1060
+ * @example
1061
+ * ```typescript
1062
+ * const original = { key1: 'value1', key2: 'value2' };
1063
+ * const reversed = reverseMap(original);
1064
+ * // reversed = { value1: 'key1', value2: 'key2' }
1065
+ * ```
1066
+ */
1067
+ function reverseMap(map) {
1068
+ return Object.entries(map).reduce((acc, [key, value]) => {
1069
+ acc[value] = key;
1070
+ return acc;
1071
+ }, {});
1072
+ }
1073
+
1074
+ /**
1075
+ * Constants used throughout the pagination system
1076
+ */
1077
+ /** Maximum number of items that can be requested in a single page */
1078
+ const MAX_PAGE_SIZE = 1000;
1079
+ /** Default page size when jumpToPage is used without specifying pageSize */
1080
+ const DEFAULT_PAGE_SIZE = 50;
1081
+ /** Default field name for items in a paginated response */
1082
+ const DEFAULT_ITEMS_FIELD = 'value';
1083
+ /** Default field name for total count in a paginated response */
1084
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1085
+ /**
1086
+ * Limits the page size to the maximum allowed value
1087
+ * @param pageSize - Requested page size
1088
+ * @returns Limited page size value
1089
+ */
1090
+ function getLimitedPageSize(pageSize) {
1091
+ if (pageSize === undefined || pageSize === null) {
1092
+ return DEFAULT_PAGE_SIZE;
1093
+ }
1094
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1095
+ }
1096
+
1097
+ /**
1098
+ * Helper functions for pagination that can be used across services
1099
+ */
1100
+ class PaginationHelpers {
1101
+ /**
1102
+ * Checks if any pagination parameters are provided
1103
+ *
1104
+ * @param options - The options object to check
1105
+ * @returns True if any pagination parameter is defined, false otherwise
1106
+ */
1107
+ static hasPaginationParameters(options = {}) {
1108
+ const { cursor, pageSize, jumpToPage } = options;
1109
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1110
+ }
1111
+ /**
1112
+ * Parse a pagination cursor string into cursor data
1113
+ */
1114
+ static parseCursor(cursorString) {
1115
+ try {
1116
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1117
+ return cursorData;
1118
+ }
1119
+ catch {
1120
+ throw new Error('Invalid pagination cursor');
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Validates cursor format and structure
1125
+ *
1126
+ * @param paginationOptions - The pagination options containing the cursor
1127
+ * @param paginationType - Optional pagination type to validate against
1128
+ */
1129
+ static validateCursor(paginationOptions, paginationType) {
1130
+ if (paginationOptions.cursor !== undefined) {
1131
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1132
+ throw new Error('cursor must contain a valid cursor string');
1133
+ }
1134
+ try {
1135
+ // Try to parse the cursor to validate it
1136
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1137
+ // If type is provided, validate cursor contains expected type information
1138
+ if (paginationType) {
1139
+ if (!cursorData.type) {
1140
+ throw new Error('Invalid cursor: missing pagination type');
1141
+ }
1142
+ // Check pagination type compatibility
1143
+ if (cursorData.type !== paginationType) {
1144
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1145
+ }
1146
+ }
1147
+ }
1148
+ catch (error) {
1149
+ if (error instanceof Error) {
1150
+ // If it's already our error with specific message, pass it through
1151
+ if (error.message.startsWith('Invalid cursor') ||
1152
+ error.message.startsWith('Pagination type mismatch')) {
1153
+ throw error;
1154
+ }
1155
+ }
1156
+ throw new Error('Invalid pagination cursor format');
1157
+ }
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Comprehensive validation for pagination options
1162
+ *
1163
+ * @param options - The pagination options to validate
1164
+ * @param paginationType - The pagination type these options will be used with
1165
+ * @returns Processed pagination parameters ready for use
1166
+ */
1167
+ static validatePaginationOptions(options, paginationType) {
1168
+ // Validate pageSize
1169
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1170
+ throw new Error('pageSize must be a positive number');
1171
+ }
1172
+ // Validate jumpToPage
1173
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1174
+ throw new Error('jumpToPage must be a positive number');
1175
+ }
1176
+ // Validate cursor
1177
+ PaginationHelpers.validateCursor(options, paginationType);
1178
+ // Validate service compatibility
1179
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1180
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1181
+ }
1182
+ // Get processed parameters
1183
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1184
+ }
1185
+ /**
1186
+ * Convert a unified pagination options to service-specific parameters
1187
+ */
1188
+ static getRequestParameters(options, paginationType) {
1189
+ // Handle jumpToPage
1190
+ if (options.jumpToPage !== undefined) {
1191
+ const jumpToPageOptions = {
1192
+ pageSize: options.pageSize,
1193
+ pageNumber: options.jumpToPage
1194
+ };
1195
+ return filterUndefined(jumpToPageOptions);
1196
+ }
1197
+ // If no cursor is provided, it's a first page request
1198
+ if (!options.cursor) {
1199
+ const firstPageOptions = {
1200
+ pageSize: options.pageSize,
1201
+ // Only set pageNumber for OFFSET pagination
1202
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1203
+ };
1204
+ return filterUndefined(firstPageOptions);
1205
+ }
1206
+ // Parse the cursor
1207
+ try {
1208
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1209
+ const cursorBasedOptions = {
1210
+ pageSize: cursorData.pageSize || options.pageSize,
1211
+ pageNumber: cursorData.pageNumber,
1212
+ continuationToken: cursorData.continuationToken,
1213
+ type: cursorData.type,
1214
+ };
1215
+ return filterUndefined(cursorBasedOptions);
1216
+ }
1217
+ catch {
1218
+ throw new Error('Invalid pagination cursor');
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Helper method for paginated resource retrieval
1223
+ *
1224
+ * @param params - Parameters for pagination
1225
+ * @returns Promise resolving to a paginated result
1226
+ */
1227
+ static async getAllPaginated(params) {
1228
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1229
+ const endpoint = getEndpoint(folderId);
1230
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1231
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1232
+ headers,
1233
+ params: additionalParams,
1234
+ pagination: {
1235
+ paginationType: options.paginationType || PaginationType.OFFSET,
1236
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1237
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1238
+ continuationTokenField: options.continuationTokenField,
1239
+ paginationParams: options.paginationParams
1240
+ }
1241
+ });
1242
+ // Parse items - automatically handle JSON string responses
1243
+ const rawItems = paginatedResponse.items;
1244
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1245
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1246
+ return {
1247
+ ...paginatedResponse,
1248
+ items: transformedItems
1249
+ };
1250
+ }
1251
+ /**
1252
+ * Helper method for non-paginated resource retrieval
1253
+ *
1254
+ * @param params - Parameters for non-paginated resource retrieval
1255
+ * @returns Promise resolving to an object with data and totalCount
1256
+ */
1257
+ static async getAllNonPaginated(params) {
1258
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1259
+ // Set default field names
1260
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1261
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1262
+ // Determine endpoint and headers based on folderId
1263
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1264
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1265
+ // Make the API call based on method
1266
+ let response;
1267
+ if (method === HTTP_METHODS.POST) {
1268
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1269
+ }
1270
+ else {
1271
+ response = await serviceAccess.get(endpoint, {
1272
+ params: additionalParams,
1273
+ headers
1274
+ });
1275
+ }
1276
+ // Extract and transform items from response
1277
+ const rawItems = response.data?.[itemsField];
1278
+ const totalCount = response.data?.[totalCountField];
1279
+ // Parse items - automatically handle JSON string responses
1280
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1281
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1282
+ return {
1283
+ items,
1284
+ totalCount
1285
+ };
1286
+ }
1287
+ /**
1288
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1289
+ *
1290
+ * @param config - Configuration for the getAll operation
1291
+ * @param options - Request options including pagination parameters
1292
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1293
+ */
1294
+ static async getAll(config, options) {
1295
+ const optionsWithDefaults = options || {};
1296
+ const { folderId, ...restOptions } = optionsWithDefaults;
1297
+ const cursor = options?.cursor;
1298
+ const pageSize = options?.pageSize;
1299
+ const jumpToPage = options?.jumpToPage;
1300
+ // Determine if pagination is requested
1301
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1302
+ // Process parameters (custom processing if provided, otherwise default)
1303
+ let processedOptions = restOptions;
1304
+ if (config.processParametersFn) {
1305
+ processedOptions = config.processParametersFn(restOptions, folderId);
1306
+ }
1307
+ // Apply ODATA prefix to keys (excluding specified keys)
1308
+ const excludeKeys = config.excludeFromPrefix || [];
1309
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1310
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1311
+ // Default pagination options
1312
+ const paginationOptions = {
1313
+ paginationType: PaginationType.OFFSET,
1314
+ itemsField: DEFAULT_ITEMS_FIELD,
1315
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1316
+ ...config.pagination
1317
+ };
1318
+ // Paginated flow
1319
+ if (isPaginationRequested) {
1320
+ return PaginationHelpers.getAllPaginated({
1321
+ serviceAccess: config.serviceAccess,
1322
+ getEndpoint: config.getEndpoint,
1323
+ folderId,
1324
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1325
+ additionalParams: prefixedOptions,
1326
+ transformFn: config.transformFn,
1327
+ method: config.method,
1328
+ options: {
1329
+ ...paginationOptions,
1330
+ paginationParams: config.pagination?.paginationParams
1331
+ }
1332
+ }); // Type assertion needed due to conditional return
1333
+ }
1334
+ // Non-paginated flow
1335
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1336
+ return PaginationHelpers.getAllNonPaginated({
1337
+ serviceAccess: config.serviceAccess,
1338
+ getAllEndpoint: config.getEndpoint(),
1339
+ getByFolderEndpoint: byFolderEndpoint,
1340
+ folderId,
1341
+ additionalParams: prefixedOptions,
1342
+ transformFn: config.transformFn,
1343
+ method: config.method,
1344
+ options: {
1345
+ itemsField: paginationOptions.itemsField,
1346
+ totalCountField: paginationOptions.totalCountField
1347
+ }
1348
+ });
1349
+ }
1350
+ }
1351
+
1352
+ /**
1353
+ * SDK Internals Registry - Internal registry for SDK instances
1354
+ *
1355
+ * This class is NOT exported in the public API.
1356
+ * It provides a secure way to share SDK internals between
1357
+ * the UiPath class and service classes without exposing them publicly.
1358
+ *
1359
+ * @internal
1360
+ */
1361
+ // Global symbol key to ensure WeakMap is shared across module instances
1362
+ // This prevents issues when core and service modules are bundled separately
1363
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1364
+ // Get or create the global WeakMap store
1365
+ const getGlobalStore = () => {
1366
+ const globalObj = globalThis;
1367
+ if (!globalObj[REGISTRY_KEY]) {
1368
+ globalObj[REGISTRY_KEY] = new WeakMap();
1369
+ }
1370
+ return globalObj[REGISTRY_KEY];
1371
+ };
1372
+ /**
1373
+ * Internal registry for SDK private components.
1374
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1375
+ * garbage collected when the SDK instance is no longer referenced.
1376
+ *
1377
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1378
+ * across separately bundled modules (core, entities, tasks, etc.).
1379
+ *
1380
+ * @internal - Not exported in public API
1381
+ */
1382
+ class SDKInternalsRegistry {
1383
+ // Use global store to ensure sharing across module bundles
1384
+ static get store() {
1385
+ return getGlobalStore();
1386
+ }
1387
+ /**
1388
+ * Register SDK instance internals
1389
+ * Called by UiPath constructor
1390
+ */
1391
+ static set(instance, internals) {
1392
+ this.store.set(instance, internals);
1393
+ }
1394
+ /**
1395
+ * Retrieve SDK instance internals
1396
+ * Called by BaseService constructor
1397
+ */
1398
+ static get(instance) {
1399
+ const internals = this.store.get(instance);
1400
+ if (!internals) {
1401
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1402
+ }
1403
+ return internals;
1404
+ }
1405
+ }
1406
+
1407
+ var _BaseService_apiClient;
1408
+ /**
1409
+ * Base class for all UiPath SDK services.
1410
+ *
1411
+ * Provides common functionality for authentication, configuration, and API communication.
1412
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1413
+ *
1414
+ * This class implements the dependency injection pattern where services receive a configured
1415
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1416
+ * including authentication token management.
1417
+ *
1418
+ * @remarks
1419
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1420
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1421
+ *
1422
+ */
1423
+ class BaseService {
1424
+ /**
1425
+ * Creates a base service instance with dependency injection.
1426
+ *
1427
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1428
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1429
+ * and token management internally.
1430
+ *
1431
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1432
+ * Services receive this via dependency injection in the modular pattern.
1433
+ *
1434
+ * @example
1435
+ * ```typescript
1436
+ * // Services automatically call this via super()
1437
+ * export class EntityService extends BaseService {
1438
+ * constructor(instance: IUiPath) {
1439
+ * super(instance); // Initializes the internal ApiClient
1440
+ * }
1441
+ * }
1442
+ *
1443
+ * // Usage in modular pattern
1444
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1445
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1446
+ *
1447
+ * const sdk = new UiPath(config);
1448
+ * await sdk.initialize();
1449
+ * const entities = new Entities(sdk);
1450
+ * ```
1451
+ */
1452
+ constructor(instance) {
1453
+ // Private field - not visible via Object.keys() or any reflection
1454
+ _BaseService_apiClient.set(this, void 0);
1455
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1456
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1457
+ }
1458
+ /**
1459
+ * Gets a valid authentication token, refreshing if necessary.
1460
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1461
+ *
1462
+ * @returns Promise resolving to a valid access token string
1463
+ * @throws AuthenticationError if no token is available or refresh fails
1464
+ */
1465
+ async getValidAuthToken() {
1466
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1467
+ }
1468
+ /**
1469
+ * Creates a service accessor for pagination helpers
1470
+ * This allows pagination helpers to access protected methods without making them public
1471
+ */
1472
+ createPaginationServiceAccess() {
1473
+ return {
1474
+ get: (path, options) => this.get(path, options || {}),
1475
+ post: (path, body, options) => this.post(path, body, options || {}),
1476
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1477
+ };
1478
+ }
1479
+ async request(method, path, options = {}) {
1480
+ switch (method.toUpperCase()) {
1481
+ case 'GET':
1482
+ return this.get(path, options);
1483
+ case 'POST':
1484
+ return this.post(path, options.body, options);
1485
+ case 'PUT':
1486
+ return this.put(path, options.body, options);
1487
+ case 'PATCH':
1488
+ return this.patch(path, options.body, options);
1489
+ case 'DELETE':
1490
+ return this.delete(path, options);
1491
+ default:
1492
+ throw new Error(`Unsupported HTTP method: ${method}`);
1493
+ }
1494
+ }
1495
+ async requestWithSpec(spec) {
1496
+ if (!spec.method || !spec.url) {
1497
+ throw new Error('Request spec must include method and url');
1498
+ }
1499
+ return this.request(spec.method, spec.url, spec);
1500
+ }
1501
+ async get(path, options = {}) {
1502
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1503
+ return { data: response };
1504
+ }
1505
+ async post(path, data, options = {}) {
1506
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1507
+ return { data: response };
1508
+ }
1509
+ async put(path, data, options = {}) {
1510
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1511
+ return { data: response };
1512
+ }
1513
+ async patch(path, data, options = {}) {
1514
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1515
+ return { data: response };
1516
+ }
1517
+ async delete(path, options = {}) {
1518
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1519
+ return { data: response };
1520
+ }
1521
+ /**
1522
+ * Execute a request with cursor-based pagination
1523
+ */
1524
+ async requestWithPagination(method, path, paginationOptions, options) {
1525
+ const paginationType = options.pagination.paginationType;
1526
+ // Validate and prepare pagination parameters
1527
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1528
+ // Prepare request parameters based on pagination type
1529
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1530
+ // For POST requests, merge pagination params into body; for GET, use query params
1531
+ if (method.toUpperCase() === 'POST') {
1532
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1533
+ options.body = {
1534
+ ...existingBody,
1535
+ ...options.params,
1536
+ ...requestParams
1537
+ };
1538
+ }
1539
+ else {
1540
+ // Merge pagination parameters with existing parameters
1541
+ options.params = {
1542
+ ...options.params,
1543
+ ...requestParams
1544
+ };
1545
+ }
1546
+ // Make the request
1547
+ const response = await this.request(method, path, options);
1548
+ // Extract data from the response and create page result
1549
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1550
+ itemsField: options.pagination.itemsField,
1551
+ totalCountField: options.pagination.totalCountField,
1552
+ continuationTokenField: options.pagination.continuationTokenField
1553
+ });
1554
+ }
1555
+ /**
1556
+ * Validates and prepares pagination parameters from options
1557
+ */
1558
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1559
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1560
+ }
1561
+ /**
1562
+ * Prepares request parameters for pagination based on pagination type
1563
+ */
1564
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1565
+ const requestParams = {};
1566
+ let limitedPageSize;
1567
+ const paginationParams = paginationConfig?.paginationParams;
1568
+ switch (paginationType) {
1569
+ case PaginationType.OFFSET:
1570
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1571
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1572
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1573
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1574
+ requestParams[pageSizeParam] = limitedPageSize;
1575
+ if (params.pageNumber && params.pageNumber > 1) {
1576
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1577
+ }
1578
+ // Include total count for ODATA APIs
1579
+ {
1580
+ requestParams[countParam] = true;
1581
+ }
1582
+ break;
1583
+ case PaginationType.TOKEN:
1584
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1585
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1586
+ if (params.pageSize) {
1587
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1588
+ }
1589
+ if (params.continuationToken) {
1590
+ requestParams[tokenParam] = params.continuationToken;
1591
+ }
1592
+ break;
1593
+ }
1594
+ return requestParams;
1595
+ }
1596
+ /**
1597
+ * Creates a paginated response from API response
1598
+ */
1599
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1600
+ // Extract fields from response
1601
+ const itemsField = fields.itemsField ||
1602
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1603
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1604
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1605
+ // Extract items and metadata
1606
+ const items = response.data[itemsField] || [];
1607
+ const totalCount = response.data[totalCountField];
1608
+ const continuationToken = response.data[continuationTokenField];
1609
+ // Determine if there are more pages
1610
+ const hasMore = this.determineHasMorePages(paginationType, {
1611
+ totalCount,
1612
+ pageSize: params.pageSize,
1613
+ currentPage: params.pageNumber || 1,
1614
+ itemsCount: items.length,
1615
+ continuationToken
1616
+ });
1617
+ // Create and return the page result
1618
+ return PaginationManager.createPaginatedResponse({
1619
+ pageInfo: {
1620
+ hasMore,
1621
+ totalCount,
1622
+ currentPage: params.pageNumber,
1623
+ pageSize: params.pageSize,
1624
+ continuationToken
1625
+ },
1626
+ type: paginationType,
1627
+ }, items);
1628
+ }
1629
+ /**
1630
+ * Determines if there are more pages based on pagination type and metadata
1631
+ */
1632
+ determineHasMorePages(paginationType, info) {
1633
+ switch (paginationType) {
1634
+ case PaginationType.OFFSET:
1635
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1636
+ // If totalCount is available, use it for precise calculation
1637
+ if (info.totalCount !== undefined) {
1638
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1639
+ }
1640
+ // Fallback when totalCount is not available
1641
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1642
+ return info.itemsCount === effectivePageSize;
1643
+ case PaginationType.TOKEN:
1644
+ return !!info.continuationToken;
1645
+ default:
1646
+ return false;
1647
+ }
1648
+ }
1649
+ }
1650
+ _BaseService_apiClient = new WeakMap();
1651
+
1652
+ /**
1653
+ * Maps fields for Process entities to ensure consistent naming
1654
+ */
1655
+ const ProcessMap = {
1656
+ lastModificationTime: 'lastModifiedTime',
1657
+ creationTime: 'createdTime',
1658
+ organizationUnitId: 'folderId',
1659
+ organizationUnitFullyQualifiedName: 'folderName',
1660
+ releaseKey: 'processKey',
1661
+ releaseName: 'processName',
1662
+ releaseVersionId: 'processVersionId',
1663
+ processType: 'packageType',
1664
+ processKey: 'packageKey',
1665
+ processVersion: 'packageVersion',
1666
+ isProcessDeleted: 'isPackageDeleted',
1667
+ };
1668
+
1669
+ /**
1670
+ * API Endpoint Constants
1671
+ * Centralized location for all API endpoints used throughout the SDK
1672
+ */
1673
+ /**
1674
+ * Base path constants for different services
1675
+ */
1676
+ const ORCHESTRATOR_BASE = 'orchestrator_';
1677
+ /**
1678
+ * Orchestrator Process Service Endpoints
1679
+ */
1680
+ const PROCESS_ENDPOINTS = {
1681
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/Releases`,
1682
+ START_PROCESS: `${ORCHESTRATOR_BASE}/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs`,
1683
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/Releases(${id})`,
1684
+ };
1685
+
1686
+ /**
1687
+ * SDK Telemetry constants
1688
+ */
1689
+ // Connection string placeholder that will be replaced during build
1690
+ const CONNECTION_STRING = "InstrumentationKey=a6efa11d-1feb-4508-9738-e13e12dcae5e;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=7c58eb1c-9581-4ba6-839e-11725848a037";
1691
+ // SDK Version placeholder
1692
+ const SDK_VERSION = "1.0.0";
1693
+ const VERSION = "Version";
1694
+ const SERVICE = "Service";
1695
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1696
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1697
+ const CLOUD_URL = "CloudUrl";
1698
+ const CLOUD_CLIENT_ID = "CloudClientId";
1699
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1700
+ const APP_NAME = "ApplicationName";
1701
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1702
+ // Service and logger names
1703
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1704
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1705
+ // Event names
1706
+ const SDK_RUN_EVENT = "Sdk.Run";
1707
+ // Default value for unknown/empty attributes
1708
+ const UNKNOWN = "";
1709
+
1710
+ /**
1711
+ * Log exporter that sends ALL logs as Application Insights custom events
1712
+ */
1713
+ class ApplicationInsightsEventExporter {
1714
+ constructor(connectionString) {
1715
+ this.connectionString = connectionString;
1716
+ }
1717
+ export(logs, resultCallback) {
1718
+ try {
1719
+ logs.forEach(logRecord => {
1720
+ this.sendAsCustomEvent(logRecord);
1721
+ });
1722
+ resultCallback({ code: 0 });
1723
+ }
1724
+ catch (error) {
1725
+ console.debug('Failed to export logs to Application Insights:', error);
1726
+ resultCallback({ code: 2, error });
1727
+ }
1728
+ }
1729
+ shutdown() {
1730
+ return Promise.resolve();
1731
+ }
1732
+ sendAsCustomEvent(logRecord) {
1733
+ // Get event name from body or attributes
1734
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1735
+ const payload = {
1736
+ name: 'Microsoft.ApplicationInsights.Event',
1737
+ time: new Date().toISOString(),
1738
+ iKey: this.extractInstrumentationKey(),
1739
+ data: {
1740
+ baseType: 'EventData',
1741
+ baseData: {
1742
+ ver: 2,
1743
+ name: eventName,
1744
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1745
+ }
1746
+ },
1747
+ tags: {
1748
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1749
+ 'ai.cloud.roleInstance': SDK_VERSION
1750
+ }
1751
+ };
1752
+ this.sendToApplicationInsights(payload);
1753
+ }
1754
+ extractInstrumentationKey() {
1755
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1756
+ return match ? match[1] : '';
1757
+ }
1758
+ convertAttributesToProperties(attributes) {
1759
+ const properties = {};
1760
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1761
+ properties[key] = String(value);
1762
+ });
1763
+ return properties;
1764
+ }
1765
+ async sendToApplicationInsights(payload) {
1766
+ try {
1767
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1768
+ if (!ingestionEndpoint) {
1769
+ console.debug('No ingestion endpoint found in connection string');
1770
+ return;
1771
+ }
1772
+ const url = `${ingestionEndpoint}/v2/track`;
1773
+ const response = await fetch(url, {
1774
+ method: 'POST',
1775
+ headers: {
1776
+ 'Content-Type': 'application/json',
1777
+ },
1778
+ body: JSON.stringify(payload)
1779
+ });
1780
+ if (!response.ok) {
1781
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1782
+ }
1783
+ }
1784
+ catch (error) {
1785
+ console.debug('Error sending event telemetry to Application Insights:', error);
1786
+ }
1787
+ }
1788
+ extractIngestionEndpoint() {
1789
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1790
+ return match ? match[1] : '';
1791
+ }
1792
+ }
1793
+ /**
1794
+ * Singleton telemetry client
1795
+ */
1796
+ class TelemetryClient {
1797
+ constructor() {
1798
+ this.isInitialized = false;
1799
+ }
1800
+ static getInstance() {
1801
+ if (!TelemetryClient.instance) {
1802
+ TelemetryClient.instance = new TelemetryClient();
1803
+ }
1804
+ return TelemetryClient.instance;
1805
+ }
1806
+ /**
1807
+ * Initialize telemetry
1808
+ */
1809
+ initialize(config) {
1810
+ if (this.isInitialized) {
1811
+ return;
1812
+ }
1813
+ this.isInitialized = true;
1814
+ if (config) {
1815
+ this.telemetryContext = config;
1816
+ }
1817
+ try {
1818
+ const connectionString = this.getConnectionString();
1819
+ if (!connectionString) {
1820
+ return;
1821
+ }
1822
+ this.setupTelemetryProvider(connectionString);
1823
+ }
1824
+ catch (error) {
1825
+ // Silent failure - telemetry errors shouldn't break functionality
1826
+ console.debug('Failed to initialize OpenTelemetry:', error);
1827
+ }
1828
+ }
1829
+ getConnectionString() {
1830
+ const connectionString = CONNECTION_STRING;
1831
+ return connectionString;
1832
+ }
1833
+ setupTelemetryProvider(connectionString) {
1834
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1835
+ const processor = new BatchLogRecordProcessor(exporter);
1836
+ this.logProvider = new LoggerProvider({
1837
+ processors: [processor]
1838
+ });
1839
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1840
+ }
1841
+ /**
1842
+ * Track a telemetry event
1843
+ */
1844
+ track(eventName, name, extraAttributes = {}) {
1845
+ try {
1846
+ // Skip if logger not initialized
1847
+ if (!this.logger) {
1848
+ return;
1849
+ }
1850
+ const finalDisplayName = name || eventName;
1851
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1852
+ // Emit as log
1853
+ this.logger.emit({
1854
+ body: finalDisplayName,
1855
+ attributes: attributes,
1856
+ timestamp: Date.now(),
1857
+ });
1858
+ }
1859
+ catch (error) {
1860
+ // Silent failure
1861
+ console.debug('Failed to track telemetry event:', error);
1862
+ }
1863
+ }
1864
+ /**
1865
+ * Get enriched attributes for telemetry events
1866
+ */
1867
+ getEnrichedAttributes(extraAttributes, eventName) {
1868
+ const attributes = {
1869
+ ...extraAttributes,
1870
+ [APP_NAME]: SDK_SERVICE_NAME,
1871
+ [VERSION]: SDK_VERSION,
1872
+ [SERVICE]: eventName,
1873
+ [CLOUD_URL]: this.createCloudUrl(),
1874
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1875
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1876
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1877
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1878
+ };
1879
+ return attributes;
1880
+ }
1881
+ /**
1882
+ * Create cloud URL from base URL, organization ID, and tenant ID
1883
+ */
1884
+ createCloudUrl() {
1885
+ const baseUrl = this.telemetryContext?.baseUrl;
1886
+ const orgId = this.telemetryContext?.orgName;
1887
+ const tenantId = this.telemetryContext?.tenantName;
1888
+ if (!baseUrl || !orgId || !tenantId) {
1889
+ return UNKNOWN;
1890
+ }
1891
+ return `${baseUrl}/${orgId}/${tenantId}`;
1892
+ }
1893
+ }
1894
+ // Export singleton instance
1895
+ const telemetryClient = TelemetryClient.getInstance();
1896
+
1897
+ /**
1898
+ * SDK Track decorator and function for telemetry
1899
+ */
1900
+ /**
1901
+ * Common tracking logic shared between method and function decorators
1902
+ */
1903
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1904
+ return function (...args) {
1905
+ // Determine if we should track this call
1906
+ let shouldTrack = true;
1907
+ if (opts.condition !== undefined) {
1908
+ if (typeof opts.condition === 'function') {
1909
+ shouldTrack = opts.condition.apply(this, args);
1910
+ }
1911
+ else {
1912
+ shouldTrack = opts.condition;
1913
+ }
1914
+ }
1915
+ // Track the event if enabled
1916
+ if (shouldTrack) {
1917
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1918
+ const serviceMethod = typeof nameOrOptions === 'string'
1919
+ ? nameOrOptions
1920
+ : fallbackName;
1921
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1922
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1923
+ }
1924
+ // Execute the original function
1925
+ return originalFunction.apply(this, args);
1926
+ };
1927
+ }
1928
+ /**
1929
+ * Track decorator that can be used to automatically track function calls
1930
+ *
1931
+ * Usage:
1932
+ * @track("Service.Method")
1933
+ * function myFunction() { ... }
1934
+ *
1935
+ * @track("Queue.GetAll")
1936
+ * async getAll() { ... }
1937
+ *
1938
+ * @track("Tasks.Create")
1939
+ * async create() { ... }
1940
+ *
1941
+ * @track("Assets.Update", { condition: false })
1942
+ * function myFunction() { ... }
1943
+ *
1944
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
1945
+ * function myFunction() { ... }
1946
+ */
1947
+ function track(nameOrOptions, options) {
1948
+ return function decorator(_target, propertyKey, descriptor) {
1949
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
1950
+ if (descriptor && typeof descriptor.value === 'function') {
1951
+ // Method decorator
1952
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
1953
+ return descriptor;
1954
+ }
1955
+ // Function decorator
1956
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
1957
+ };
1958
+ }
1959
+
1960
+ /**
1961
+ * Service for interacting with UiPath Orchestrator Processes API
1962
+ */
1963
+ class ProcessService extends BaseService {
1964
+ /**
1965
+ * Gets all processes across folders with optional filtering and folder scoping
1966
+ *
1967
+ * The method returns either:
1968
+ * - An array of processes (when no pagination parameters are provided)
1969
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
1970
+ *
1971
+ * @param options - Query options including optional folderId
1972
+ * @returns Promise resolving to an array of processes or paginated result
1973
+ *
1974
+ * @example
1975
+ * ```typescript
1976
+ * import { Processes } from '@uipath/uipath-typescript/processes';
1977
+ *
1978
+ * const processes = new Processes(sdk);
1979
+ *
1980
+ * // Standard array return
1981
+ * const allProcesses = await processes.getAll();
1982
+ *
1983
+ * // Get processes within a specific folder
1984
+ * const folderProcesses = await processes.getAll({
1985
+ * folderId: 123
1986
+ * });
1987
+ *
1988
+ * // Get processes with filtering
1989
+ * const filteredProcesses = await processes.getAll({
1990
+ * filter: "name eq 'MyProcess'"
1991
+ * });
1992
+ *
1993
+ * // First page with pagination
1994
+ * const page1 = await processes.getAll({ pageSize: 10 });
1995
+ *
1996
+ * // Navigate using cursor
1997
+ * if (page1.hasNextPage) {
1998
+ * const page2 = await processes.getAll({ cursor: page1.nextCursor });
1999
+ * }
2000
+ *
2001
+ * // Jump to specific page
2002
+ * const page5 = await processes.getAll({
2003
+ * jumpToPage: 5,
2004
+ * pageSize: 10
2005
+ * });
2006
+ * ```
2007
+ */
2008
+ async getAll(options) {
2009
+ // Transformation function for processes
2010
+ const transformProcessResponse = (process) => transformData(pascalToCamelCaseKeys(process), ProcessMap);
2011
+ return PaginationHelpers.getAll({
2012
+ serviceAccess: this.createPaginationServiceAccess(),
2013
+ getEndpoint: () => PROCESS_ENDPOINTS.GET_ALL,
2014
+ getByFolderEndpoint: PROCESS_ENDPOINTS.GET_ALL, // Processes use same endpoint for both
2015
+ transformFn: transformProcessResponse,
2016
+ pagination: {
2017
+ paginationType: PaginationType.OFFSET,
2018
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2019
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2020
+ paginationParams: {
2021
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2022
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2023
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
2024
+ }
2025
+ }
2026
+ }, options);
2027
+ }
2028
+ /**
2029
+ * Starts a process execution (job)
2030
+ *
2031
+ * @param request - Process start request body
2032
+ * @param folderId - Required folder ID
2033
+ * @param options - Optional query parameters
2034
+ * @returns Promise resolving to the created jobs
2035
+ *
2036
+ * @example
2037
+ * ```typescript
2038
+ * import { Processes } from '@uipath/uipath-typescript/processes';
2039
+ *
2040
+ * const processes = new Processes(sdk);
2041
+ *
2042
+ * // Start a process by process key
2043
+ * const jobs = await processes.start({
2044
+ * processKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
2045
+ * }, 123); // folderId is required
2046
+ *
2047
+ * // Start a process by name with specific robots
2048
+ * const jobs = await processes.start({
2049
+ * processName: "MyProcess"
2050
+ * }, 123); // folderId is required
2051
+ * ```
2052
+ */
2053
+ async start(request, folderId, options = {}) {
2054
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2055
+ // Transform processKey/processName to releaseKey/releaseName for API compatibility
2056
+ const apiRequest = { ...request };
2057
+ // Create a reverse mapping using ProcessMap
2058
+ const reversedPropertiesMap = reverseMap(ProcessMap);
2059
+ // Apply transformations for any client properties found in the request
2060
+ Object.entries(reversedPropertiesMap).forEach(([clientKey, apiKey]) => {
2061
+ if (clientKey in apiRequest) {
2062
+ apiRequest[apiKey] = apiRequest[clientKey];
2063
+ delete apiRequest[clientKey];
2064
+ }
2065
+ });
2066
+ // Create the request object according to API spec
2067
+ const requestBody = {
2068
+ startInfo: apiRequest
2069
+ };
2070
+ // Prefix all query parameter keys with '$' for OData
2071
+ const keysToPrefix = Object.keys(options);
2072
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
2073
+ const response = await this.post(PROCESS_ENDPOINTS.START_PROCESS, requestBody, {
2074
+ params: apiOptions,
2075
+ headers
2076
+ });
2077
+ const transformedProcess = response.data?.value.map(process => transformData(pascalToCamelCaseKeys(process), ProcessMap));
2078
+ return transformedProcess;
2079
+ }
2080
+ /**
2081
+ * Gets a single process by ID
2082
+ *
2083
+ * @param id - Process ID
2084
+ * @param folderId - Required folder ID
2085
+ * @param options - Optional query parameters
2086
+ * @returns Promise resolving to a single process
2087
+ *
2088
+ * @example
2089
+ * ```typescript
2090
+ * import { Processes } from '@uipath/uipath-typescript/processes';
2091
+ *
2092
+ * const processes = new Processes(sdk);
2093
+ *
2094
+ * // Get process by ID
2095
+ * const process = await processes.getById(123, 456);
2096
+ * ```
2097
+ */
2098
+ async getById(id, folderId, options = {}) {
2099
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2100
+ const keysToPrefix = Object.keys(options);
2101
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
2102
+ const response = await this.get(PROCESS_ENDPOINTS.GET_BY_ID(id), {
2103
+ headers,
2104
+ params: apiOptions
2105
+ });
2106
+ const transformedProcess = transformData(pascalToCamelCaseKeys(response.data), ProcessMap);
2107
+ return transformedProcess;
2108
+ }
2109
+ }
2110
+ __decorate([
2111
+ track('Processes.GetAll')
2112
+ ], ProcessService.prototype, "getAll", null);
2113
+ __decorate([
2114
+ track('Processes.Start')
2115
+ ], ProcessService.prototype, "start", null);
2116
+ __decorate([
2117
+ track('Processes.GetById')
2118
+ ], ProcessService.prototype, "getById", null);
2119
+
2120
+ /**
2121
+ * Enum for package types
2122
+ */
2123
+ var PackageType;
2124
+ (function (PackageType) {
2125
+ PackageType["Undefined"] = "Undefined";
2126
+ PackageType["Process"] = "Process";
2127
+ PackageType["ProcessOrchestration"] = "ProcessOrchestration";
2128
+ PackageType["WebApp"] = "WebApp";
2129
+ PackageType["Agent"] = "Agent";
2130
+ PackageType["TestAutomationProcess"] = "TestAutomationProcess";
2131
+ PackageType["Api"] = "Api";
2132
+ PackageType["MCPServer"] = "MCPServer";
2133
+ PackageType["BusinessRules"] = "BusinessRules";
2134
+ })(PackageType || (PackageType = {}));
2135
+ /**
2136
+ * Enum for job priority
2137
+ */
2138
+ var JobPriority;
2139
+ (function (JobPriority) {
2140
+ JobPriority["Low"] = "Low";
2141
+ JobPriority["Normal"] = "Normal";
2142
+ JobPriority["High"] = "High";
2143
+ })(JobPriority || (JobPriority = {}));
2144
+ /**
2145
+ * Enum for target framework
2146
+ */
2147
+ var TargetFramework;
2148
+ (function (TargetFramework) {
2149
+ TargetFramework["Legacy"] = "Legacy";
2150
+ TargetFramework["Windows"] = "Windows";
2151
+ TargetFramework["Portable"] = "Portable";
2152
+ })(TargetFramework || (TargetFramework = {}));
2153
+ /**
2154
+ * Enum for robot size
2155
+ */
2156
+ var RobotSize;
2157
+ (function (RobotSize) {
2158
+ RobotSize["Small"] = "Small";
2159
+ RobotSize["Standard"] = "Standard";
2160
+ RobotSize["Medium"] = "Medium";
2161
+ RobotSize["Large"] = "Large";
2162
+ })(RobotSize || (RobotSize = {}));
2163
+ /**
2164
+ * Enum for remote control access
2165
+ */
2166
+ var RemoteControlAccess;
2167
+ (function (RemoteControlAccess) {
2168
+ RemoteControlAccess["None"] = "None";
2169
+ RemoteControlAccess["ReadOnly"] = "ReadOnly";
2170
+ RemoteControlAccess["Full"] = "Full";
2171
+ })(RemoteControlAccess || (RemoteControlAccess = {}));
2172
+ /**
2173
+ * Enum for process start strategy
2174
+ */
2175
+ var StartStrategy;
2176
+ (function (StartStrategy) {
2177
+ StartStrategy["All"] = "All";
2178
+ StartStrategy["Specific"] = "Specific";
2179
+ StartStrategy["RobotCount"] = "RobotCount";
2180
+ StartStrategy["JobsCount"] = "JobsCount";
2181
+ StartStrategy["ModernJobsCount"] = "ModernJobsCount";
2182
+ })(StartStrategy || (StartStrategy = {}));
2183
+ /**
2184
+ * Enum for package source type
2185
+ */
2186
+ var PackageSourceType;
2187
+ (function (PackageSourceType) {
2188
+ PackageSourceType["Manual"] = "Manual";
2189
+ PackageSourceType["Schedule"] = "Schedule";
2190
+ PackageSourceType["Queue"] = "Queue";
2191
+ PackageSourceType["StudioWeb"] = "StudioWeb";
2192
+ PackageSourceType["IntegrationTrigger"] = "IntegrationTrigger";
2193
+ PackageSourceType["StudioDesktop"] = "StudioDesktop";
2194
+ PackageSourceType["AutomationOpsPipelines"] = "AutomationOpsPipelines";
2195
+ PackageSourceType["Apps"] = "Apps";
2196
+ PackageSourceType["SAP"] = "SAP";
2197
+ PackageSourceType["HttpTrigger"] = "HttpTrigger";
2198
+ PackageSourceType["HttpTriggerWithCallback"] = "HttpTriggerWithCallback";
2199
+ PackageSourceType["RobotAPI"] = "RobotAPI";
2200
+ PackageSourceType["Assistant"] = "Assistant";
2201
+ PackageSourceType["CommandLine"] = "CommandLine";
2202
+ PackageSourceType["RobotNetAPI"] = "RobotNetAPI";
2203
+ PackageSourceType["Autopilot"] = "Autopilot";
2204
+ PackageSourceType["TestManager"] = "TestManager";
2205
+ PackageSourceType["AgentService"] = "AgentService";
2206
+ PackageSourceType["ProcessOrchestration"] = "ProcessOrchestration";
2207
+ PackageSourceType["PluginEcosystem"] = "PluginEcosystem";
2208
+ PackageSourceType["PerformanceTesting"] = "PerformanceTesting";
2209
+ PackageSourceType["AgentHub"] = "AgentHub";
2210
+ PackageSourceType["ApiWorkflow"] = "ApiWorkflow";
2211
+ })(PackageSourceType || (PackageSourceType = {}));
2212
+ /**
2213
+ * Enum for stop strategy
2214
+ */
2215
+ var StopStrategy;
2216
+ (function (StopStrategy) {
2217
+ StopStrategy["SoftStop"] = "SoftStop";
2218
+ StopStrategy["Kill"] = "Kill";
2219
+ })(StopStrategy || (StopStrategy = {}));
2220
+ /**
2221
+ * Enum for job type
2222
+ */
2223
+ var JobType;
2224
+ (function (JobType) {
2225
+ JobType["Unattended"] = "Unattended";
2226
+ JobType["Attended"] = "Attended";
2227
+ JobType["ServerlessGeneric"] = "ServerlessGeneric";
2228
+ })(JobType || (JobType = {}));
2229
+
2230
+ export { JobPriority, JobType, PackageSourceType, PackageType, ProcessService, ProcessService as Processes, RemoteControlAccess, RobotSize, StartStrategy, StopStrategy, TargetFramework };