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