@uipath/uipath-typescript 1.0.0-beta.18 → 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,2075 @@
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
+ /**
1059
+ * Constants used throughout the pagination system
1060
+ */
1061
+ /** Maximum number of items that can be requested in a single page */
1062
+ const MAX_PAGE_SIZE = 1000;
1063
+ /** Default page size when jumpToPage is used without specifying pageSize */
1064
+ const DEFAULT_PAGE_SIZE = 50;
1065
+ /** Default field name for items in a paginated response */
1066
+ const DEFAULT_ITEMS_FIELD = 'value';
1067
+ /** Default field name for total count in a paginated response */
1068
+ const DEFAULT_TOTAL_COUNT_FIELD = '@odata.count';
1069
+ /**
1070
+ * Limits the page size to the maximum allowed value
1071
+ * @param pageSize - Requested page size
1072
+ * @returns Limited page size value
1073
+ */
1074
+ function getLimitedPageSize(pageSize) {
1075
+ if (pageSize === undefined || pageSize === null) {
1076
+ return DEFAULT_PAGE_SIZE;
1077
+ }
1078
+ return Math.max(1, Math.min(pageSize, MAX_PAGE_SIZE));
1079
+ }
1080
+
1081
+ /**
1082
+ * Helper functions for pagination that can be used across services
1083
+ */
1084
+ class PaginationHelpers {
1085
+ /**
1086
+ * Checks if any pagination parameters are provided
1087
+ *
1088
+ * @param options - The options object to check
1089
+ * @returns True if any pagination parameter is defined, false otherwise
1090
+ */
1091
+ static hasPaginationParameters(options = {}) {
1092
+ const { cursor, pageSize, jumpToPage } = options;
1093
+ return cursor !== undefined || pageSize !== undefined || jumpToPage !== undefined;
1094
+ }
1095
+ /**
1096
+ * Parse a pagination cursor string into cursor data
1097
+ */
1098
+ static parseCursor(cursorString) {
1099
+ try {
1100
+ const cursorData = JSON.parse(decodeBase64(cursorString));
1101
+ return cursorData;
1102
+ }
1103
+ catch {
1104
+ throw new Error('Invalid pagination cursor');
1105
+ }
1106
+ }
1107
+ /**
1108
+ * Validates cursor format and structure
1109
+ *
1110
+ * @param paginationOptions - The pagination options containing the cursor
1111
+ * @param paginationType - Optional pagination type to validate against
1112
+ */
1113
+ static validateCursor(paginationOptions, paginationType) {
1114
+ if (paginationOptions.cursor !== undefined) {
1115
+ if (!paginationOptions.cursor || typeof paginationOptions.cursor.value !== 'string' || !paginationOptions.cursor.value) {
1116
+ throw new Error('cursor must contain a valid cursor string');
1117
+ }
1118
+ try {
1119
+ // Try to parse the cursor to validate it
1120
+ const cursorData = PaginationHelpers.parseCursor(paginationOptions.cursor.value);
1121
+ // If type is provided, validate cursor contains expected type information
1122
+ if (paginationType) {
1123
+ if (!cursorData.type) {
1124
+ throw new Error('Invalid cursor: missing pagination type');
1125
+ }
1126
+ // Check pagination type compatibility
1127
+ if (cursorData.type !== paginationType) {
1128
+ throw new Error(`Pagination type mismatch: cursor is for ${cursorData.type} but service uses ${paginationType}`);
1129
+ }
1130
+ }
1131
+ }
1132
+ catch (error) {
1133
+ if (error instanceof Error) {
1134
+ // If it's already our error with specific message, pass it through
1135
+ if (error.message.startsWith('Invalid cursor') ||
1136
+ error.message.startsWith('Pagination type mismatch')) {
1137
+ throw error;
1138
+ }
1139
+ }
1140
+ throw new Error('Invalid pagination cursor format');
1141
+ }
1142
+ }
1143
+ }
1144
+ /**
1145
+ * Comprehensive validation for pagination options
1146
+ *
1147
+ * @param options - The pagination options to validate
1148
+ * @param paginationType - The pagination type these options will be used with
1149
+ * @returns Processed pagination parameters ready for use
1150
+ */
1151
+ static validatePaginationOptions(options, paginationType) {
1152
+ // Validate pageSize
1153
+ if (options.pageSize !== undefined && options.pageSize <= 0) {
1154
+ throw new Error('pageSize must be a positive number');
1155
+ }
1156
+ // Validate jumpToPage
1157
+ if (options.jumpToPage !== undefined && options.jumpToPage <= 0) {
1158
+ throw new Error('jumpToPage must be a positive number');
1159
+ }
1160
+ // Validate cursor
1161
+ PaginationHelpers.validateCursor(options, paginationType);
1162
+ // Validate service compatibility
1163
+ if (options.jumpToPage !== undefined && paginationType === PaginationType.TOKEN) {
1164
+ throw new Error('jumpToPage is not supported for token-based pagination. Use cursor-based navigation instead.');
1165
+ }
1166
+ // Get processed parameters
1167
+ return PaginationHelpers.getRequestParameters(options, paginationType);
1168
+ }
1169
+ /**
1170
+ * Convert a unified pagination options to service-specific parameters
1171
+ */
1172
+ static getRequestParameters(options, paginationType) {
1173
+ // Handle jumpToPage
1174
+ if (options.jumpToPage !== undefined) {
1175
+ const jumpToPageOptions = {
1176
+ pageSize: options.pageSize,
1177
+ pageNumber: options.jumpToPage
1178
+ };
1179
+ return filterUndefined(jumpToPageOptions);
1180
+ }
1181
+ // If no cursor is provided, it's a first page request
1182
+ if (!options.cursor) {
1183
+ const firstPageOptions = {
1184
+ pageSize: options.pageSize,
1185
+ // Only set pageNumber for OFFSET pagination
1186
+ pageNumber: paginationType === PaginationType.OFFSET ? 1 : undefined
1187
+ };
1188
+ return filterUndefined(firstPageOptions);
1189
+ }
1190
+ // Parse the cursor
1191
+ try {
1192
+ const cursorData = PaginationHelpers.parseCursor(options.cursor.value);
1193
+ const cursorBasedOptions = {
1194
+ pageSize: cursorData.pageSize || options.pageSize,
1195
+ pageNumber: cursorData.pageNumber,
1196
+ continuationToken: cursorData.continuationToken,
1197
+ type: cursorData.type,
1198
+ };
1199
+ return filterUndefined(cursorBasedOptions);
1200
+ }
1201
+ catch {
1202
+ throw new Error('Invalid pagination cursor');
1203
+ }
1204
+ }
1205
+ /**
1206
+ * Helper method for paginated resource retrieval
1207
+ *
1208
+ * @param params - Parameters for pagination
1209
+ * @returns Promise resolving to a paginated result
1210
+ */
1211
+ static async getAllPaginated(params) {
1212
+ const { serviceAccess, getEndpoint, folderId, paginationParams, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1213
+ const endpoint = getEndpoint(folderId);
1214
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1215
+ const paginatedResponse = await serviceAccess.requestWithPagination(method, endpoint, paginationParams, {
1216
+ headers,
1217
+ params: additionalParams,
1218
+ pagination: {
1219
+ paginationType: options.paginationType || PaginationType.OFFSET,
1220
+ itemsField: options.itemsField || DEFAULT_ITEMS_FIELD,
1221
+ totalCountField: options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD,
1222
+ continuationTokenField: options.continuationTokenField,
1223
+ paginationParams: options.paginationParams
1224
+ }
1225
+ });
1226
+ // Parse items - automatically handle JSON string responses
1227
+ const rawItems = paginatedResponse.items;
1228
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1229
+ const transformedItems = transformFn ? parsedItems.map(transformFn) : parsedItems;
1230
+ return {
1231
+ ...paginatedResponse,
1232
+ items: transformedItems
1233
+ };
1234
+ }
1235
+ /**
1236
+ * Helper method for non-paginated resource retrieval
1237
+ *
1238
+ * @param params - Parameters for non-paginated resource retrieval
1239
+ * @returns Promise resolving to an object with data and totalCount
1240
+ */
1241
+ static async getAllNonPaginated(params) {
1242
+ const { serviceAccess, getAllEndpoint, getByFolderEndpoint, folderId, additionalParams, transformFn, method = HTTP_METHODS.GET, options = {} } = params;
1243
+ // Set default field names
1244
+ const itemsField = options.itemsField || DEFAULT_ITEMS_FIELD;
1245
+ const totalCountField = options.totalCountField || DEFAULT_TOTAL_COUNT_FIELD;
1246
+ // Determine endpoint and headers based on folderId
1247
+ const endpoint = folderId ? getByFolderEndpoint : getAllEndpoint;
1248
+ const headers = folderId ? createHeaders({ [FOLDER_ID]: folderId }) : {};
1249
+ // Make the API call based on method
1250
+ let response;
1251
+ if (method === HTTP_METHODS.POST) {
1252
+ response = await serviceAccess.post(endpoint, additionalParams, { headers });
1253
+ }
1254
+ else {
1255
+ response = await serviceAccess.get(endpoint, {
1256
+ params: additionalParams,
1257
+ headers
1258
+ });
1259
+ }
1260
+ // Extract and transform items from response
1261
+ const rawItems = response.data?.[itemsField];
1262
+ const totalCount = response.data?.[totalCountField];
1263
+ // Parse items - automatically handle JSON string responses
1264
+ const parsedItems = typeof rawItems === 'string' ? JSON.parse(rawItems) : (rawItems || []);
1265
+ const items = transformFn ? parsedItems.map(transformFn) : parsedItems;
1266
+ return {
1267
+ items,
1268
+ totalCount
1269
+ };
1270
+ }
1271
+ /**
1272
+ * Centralized getAll implementation that handles both paginated and non-paginated requests
1273
+ *
1274
+ * @param config - Configuration for the getAll operation
1275
+ * @param options - Request options including pagination parameters
1276
+ * @returns Promise resolving to either paginated or non-paginated response based on options
1277
+ */
1278
+ static async getAll(config, options) {
1279
+ const optionsWithDefaults = options || {};
1280
+ const { folderId, ...restOptions } = optionsWithDefaults;
1281
+ const cursor = options?.cursor;
1282
+ const pageSize = options?.pageSize;
1283
+ const jumpToPage = options?.jumpToPage;
1284
+ // Determine if pagination is requested
1285
+ const isPaginationRequested = PaginationHelpers.hasPaginationParameters(options || {});
1286
+ // Process parameters (custom processing if provided, otherwise default)
1287
+ let processedOptions = restOptions;
1288
+ if (config.processParametersFn) {
1289
+ processedOptions = config.processParametersFn(restOptions, folderId);
1290
+ }
1291
+ // Apply ODATA prefix to keys (excluding specified keys)
1292
+ const excludeKeys = config.excludeFromPrefix || [];
1293
+ const keysToPrefix = Object.keys(processedOptions).filter(k => !excludeKeys.includes(k));
1294
+ const prefixedOptions = addPrefixToKeys(processedOptions, ODATA_PREFIX, keysToPrefix);
1295
+ // Default pagination options
1296
+ const paginationOptions = {
1297
+ paginationType: PaginationType.OFFSET,
1298
+ itemsField: DEFAULT_ITEMS_FIELD,
1299
+ totalCountField: DEFAULT_TOTAL_COUNT_FIELD,
1300
+ ...config.pagination
1301
+ };
1302
+ // Paginated flow
1303
+ if (isPaginationRequested) {
1304
+ return PaginationHelpers.getAllPaginated({
1305
+ serviceAccess: config.serviceAccess,
1306
+ getEndpoint: config.getEndpoint,
1307
+ folderId,
1308
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
1309
+ additionalParams: prefixedOptions,
1310
+ transformFn: config.transformFn,
1311
+ method: config.method,
1312
+ options: {
1313
+ ...paginationOptions,
1314
+ paginationParams: config.pagination?.paginationParams
1315
+ }
1316
+ }); // Type assertion needed due to conditional return
1317
+ }
1318
+ // Non-paginated flow
1319
+ const byFolderEndpoint = config.getByFolderEndpoint || config.getEndpoint(folderId);
1320
+ return PaginationHelpers.getAllNonPaginated({
1321
+ serviceAccess: config.serviceAccess,
1322
+ getAllEndpoint: config.getEndpoint(),
1323
+ getByFolderEndpoint: byFolderEndpoint,
1324
+ folderId,
1325
+ additionalParams: prefixedOptions,
1326
+ transformFn: config.transformFn,
1327
+ method: config.method,
1328
+ options: {
1329
+ itemsField: paginationOptions.itemsField,
1330
+ totalCountField: paginationOptions.totalCountField
1331
+ }
1332
+ });
1333
+ }
1334
+ }
1335
+
1336
+ /**
1337
+ * SDK Internals Registry - Internal registry for SDK instances
1338
+ *
1339
+ * This class is NOT exported in the public API.
1340
+ * It provides a secure way to share SDK internals between
1341
+ * the UiPath class and service classes without exposing them publicly.
1342
+ *
1343
+ * @internal
1344
+ */
1345
+ // Global symbol key to ensure WeakMap is shared across module instances
1346
+ // This prevents issues when core and service modules are bundled separately
1347
+ const REGISTRY_KEY = Symbol.for('@uipath/sdk-internals-registry');
1348
+ // Get or create the global WeakMap store
1349
+ const getGlobalStore = () => {
1350
+ const globalObj = globalThis;
1351
+ if (!globalObj[REGISTRY_KEY]) {
1352
+ globalObj[REGISTRY_KEY] = new WeakMap();
1353
+ }
1354
+ return globalObj[REGISTRY_KEY];
1355
+ };
1356
+ /**
1357
+ * Internal registry for SDK private components.
1358
+ * Uses WeakMap to prevent memory leaks - entries are automatically
1359
+ * garbage collected when the SDK instance is no longer referenced.
1360
+ *
1361
+ * Uses a global singleton pattern to ensure the same WeakMap is shared
1362
+ * across separately bundled modules (core, entities, tasks, etc.).
1363
+ *
1364
+ * @internal - Not exported in public API
1365
+ */
1366
+ class SDKInternalsRegistry {
1367
+ // Use global store to ensure sharing across module bundles
1368
+ static get store() {
1369
+ return getGlobalStore();
1370
+ }
1371
+ /**
1372
+ * Register SDK instance internals
1373
+ * Called by UiPath constructor
1374
+ */
1375
+ static set(instance, internals) {
1376
+ this.store.set(instance, internals);
1377
+ }
1378
+ /**
1379
+ * Retrieve SDK instance internals
1380
+ * Called by BaseService constructor
1381
+ */
1382
+ static get(instance) {
1383
+ const internals = this.store.get(instance);
1384
+ if (!internals) {
1385
+ throw new Error('Invalid SDK instance. Make sure to pass a valid UiPath instance to the service constructor.');
1386
+ }
1387
+ return internals;
1388
+ }
1389
+ }
1390
+
1391
+ var _BaseService_apiClient;
1392
+ /**
1393
+ * Base class for all UiPath SDK services.
1394
+ *
1395
+ * Provides common functionality for authentication, configuration, and API communication.
1396
+ * All service classes extend this base to inherit dependency injection and HTTP client access.
1397
+ *
1398
+ * This class implements the dependency injection pattern where services receive a configured
1399
+ * UiPath instance. The ApiClient is created internally and handles all HTTP operations
1400
+ * including authentication token management.
1401
+ *
1402
+ * @remarks
1403
+ * Service classes should extend this base and call `super(uiPath)` in their constructor.
1404
+ * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses.
1405
+ *
1406
+ */
1407
+ class BaseService {
1408
+ /**
1409
+ * Creates a base service instance with dependency injection.
1410
+ *
1411
+ * Extracts configuration, execution context, and token manager from the UiPath instance
1412
+ * to initialize an authenticated API client. The ApiClient handles all HTTP operations
1413
+ * and token management internally.
1414
+ *
1415
+ * @param instance - UiPath SDK instance providing authentication and configuration.
1416
+ * Services receive this via dependency injection in the modular pattern.
1417
+ *
1418
+ * @example
1419
+ * ```typescript
1420
+ * // Services automatically call this via super()
1421
+ * export class EntityService extends BaseService {
1422
+ * constructor(instance: IUiPath) {
1423
+ * super(instance); // Initializes the internal ApiClient
1424
+ * }
1425
+ * }
1426
+ *
1427
+ * // Usage in modular pattern
1428
+ * import { UiPath } from '@uipath/uipath-typescript/core';
1429
+ * import { Entities } from '@uipath/uipath-typescript/entities';
1430
+ *
1431
+ * const sdk = new UiPath(config);
1432
+ * await sdk.initialize();
1433
+ * const entities = new Entities(sdk);
1434
+ * ```
1435
+ */
1436
+ constructor(instance) {
1437
+ // Private field - not visible via Object.keys() or any reflection
1438
+ _BaseService_apiClient.set(this, void 0);
1439
+ const { config, context, tokenManager } = SDKInternalsRegistry.get(instance);
1440
+ __classPrivateFieldSet(this, _BaseService_apiClient, new ApiClient(config, context, tokenManager), "f");
1441
+ }
1442
+ /**
1443
+ * Gets a valid authentication token, refreshing if necessary.
1444
+ * Use this when you need to manually add Authorization headers (e.g., direct uploads).
1445
+ *
1446
+ * @returns Promise resolving to a valid access token string
1447
+ * @throws AuthenticationError if no token is available or refresh fails
1448
+ */
1449
+ async getValidAuthToken() {
1450
+ return __classPrivateFieldGet(this, _BaseService_apiClient, "f").getValidToken();
1451
+ }
1452
+ /**
1453
+ * Creates a service accessor for pagination helpers
1454
+ * This allows pagination helpers to access protected methods without making them public
1455
+ */
1456
+ createPaginationServiceAccess() {
1457
+ return {
1458
+ get: (path, options) => this.get(path, options || {}),
1459
+ post: (path, body, options) => this.post(path, body, options || {}),
1460
+ requestWithPagination: (method, path, paginationOptions, options) => this.requestWithPagination(method, path, paginationOptions, options)
1461
+ };
1462
+ }
1463
+ async request(method, path, options = {}) {
1464
+ switch (method.toUpperCase()) {
1465
+ case 'GET':
1466
+ return this.get(path, options);
1467
+ case 'POST':
1468
+ return this.post(path, options.body, options);
1469
+ case 'PUT':
1470
+ return this.put(path, options.body, options);
1471
+ case 'PATCH':
1472
+ return this.patch(path, options.body, options);
1473
+ case 'DELETE':
1474
+ return this.delete(path, options);
1475
+ default:
1476
+ throw new Error(`Unsupported HTTP method: ${method}`);
1477
+ }
1478
+ }
1479
+ async requestWithSpec(spec) {
1480
+ if (!spec.method || !spec.url) {
1481
+ throw new Error('Request spec must include method and url');
1482
+ }
1483
+ return this.request(spec.method, spec.url, spec);
1484
+ }
1485
+ async get(path, options = {}) {
1486
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").get(path, options);
1487
+ return { data: response };
1488
+ }
1489
+ async post(path, data, options = {}) {
1490
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").post(path, data, options);
1491
+ return { data: response };
1492
+ }
1493
+ async put(path, data, options = {}) {
1494
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").put(path, data, options);
1495
+ return { data: response };
1496
+ }
1497
+ async patch(path, data, options = {}) {
1498
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").patch(path, data, options);
1499
+ return { data: response };
1500
+ }
1501
+ async delete(path, options = {}) {
1502
+ const response = await __classPrivateFieldGet(this, _BaseService_apiClient, "f").delete(path, options);
1503
+ return { data: response };
1504
+ }
1505
+ /**
1506
+ * Execute a request with cursor-based pagination
1507
+ */
1508
+ async requestWithPagination(method, path, paginationOptions, options) {
1509
+ const paginationType = options.pagination.paginationType;
1510
+ // Validate and prepare pagination parameters
1511
+ const params = this.validateAndPreparePaginationParams(paginationType, paginationOptions);
1512
+ // Prepare request parameters based on pagination type
1513
+ const requestParams = this.preparePaginationRequestParams(paginationType, params, options.pagination);
1514
+ // For POST requests, merge pagination params into body; for GET, use query params
1515
+ if (method.toUpperCase() === 'POST') {
1516
+ const existingBody = (options.body && typeof options.body === 'object') ? options.body : {};
1517
+ options.body = {
1518
+ ...existingBody,
1519
+ ...options.params,
1520
+ ...requestParams
1521
+ };
1522
+ }
1523
+ else {
1524
+ // Merge pagination parameters with existing parameters
1525
+ options.params = {
1526
+ ...options.params,
1527
+ ...requestParams
1528
+ };
1529
+ }
1530
+ // Make the request
1531
+ const response = await this.request(method, path, options);
1532
+ // Extract data from the response and create page result
1533
+ return this.createPaginatedResponseFromResponse(response, params, paginationType, {
1534
+ itemsField: options.pagination.itemsField,
1535
+ totalCountField: options.pagination.totalCountField,
1536
+ continuationTokenField: options.pagination.continuationTokenField
1537
+ });
1538
+ }
1539
+ /**
1540
+ * Validates and prepares pagination parameters from options
1541
+ */
1542
+ validateAndPreparePaginationParams(paginationType, paginationOptions) {
1543
+ return PaginationHelpers.validatePaginationOptions(paginationOptions, paginationType);
1544
+ }
1545
+ /**
1546
+ * Prepares request parameters for pagination based on pagination type
1547
+ */
1548
+ preparePaginationRequestParams(paginationType, params, paginationConfig) {
1549
+ const requestParams = {};
1550
+ let limitedPageSize;
1551
+ const paginationParams = paginationConfig?.paginationParams;
1552
+ switch (paginationType) {
1553
+ case PaginationType.OFFSET:
1554
+ limitedPageSize = getLimitedPageSize(params.pageSize);
1555
+ const pageSizeParam = paginationParams?.pageSizeParam || ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM;
1556
+ const offsetParam = paginationParams?.offsetParam || ODATA_OFFSET_PARAMS.OFFSET_PARAM;
1557
+ const countParam = paginationParams?.countParam || ODATA_OFFSET_PARAMS.COUNT_PARAM;
1558
+ requestParams[pageSizeParam] = limitedPageSize;
1559
+ if (params.pageNumber && params.pageNumber > 1) {
1560
+ requestParams[offsetParam] = (params.pageNumber - 1) * limitedPageSize;
1561
+ }
1562
+ // Include total count for ODATA APIs
1563
+ {
1564
+ requestParams[countParam] = true;
1565
+ }
1566
+ break;
1567
+ case PaginationType.TOKEN:
1568
+ const tokenPageSizeParam = paginationParams?.pageSizeParam || BUCKET_TOKEN_PARAMS.PAGE_SIZE_PARAM;
1569
+ const tokenParam = paginationParams?.tokenParam || BUCKET_TOKEN_PARAMS.TOKEN_PARAM;
1570
+ if (params.pageSize) {
1571
+ requestParams[tokenPageSizeParam] = getLimitedPageSize(params.pageSize);
1572
+ }
1573
+ if (params.continuationToken) {
1574
+ requestParams[tokenParam] = params.continuationToken;
1575
+ }
1576
+ break;
1577
+ }
1578
+ return requestParams;
1579
+ }
1580
+ /**
1581
+ * Creates a paginated response from API response
1582
+ */
1583
+ createPaginatedResponseFromResponse(response, params, paginationType, fields) {
1584
+ // Extract fields from response
1585
+ const itemsField = fields.itemsField ||
1586
+ (paginationType === PaginationType.TOKEN ? 'items' : 'value');
1587
+ const totalCountField = fields.totalCountField || 'totalRecordCount';
1588
+ const continuationTokenField = fields.continuationTokenField || 'continuationToken';
1589
+ // Extract items and metadata
1590
+ const items = response.data[itemsField] || [];
1591
+ const totalCount = response.data[totalCountField];
1592
+ const continuationToken = response.data[continuationTokenField];
1593
+ // Determine if there are more pages
1594
+ const hasMore = this.determineHasMorePages(paginationType, {
1595
+ totalCount,
1596
+ pageSize: params.pageSize,
1597
+ currentPage: params.pageNumber || 1,
1598
+ itemsCount: items.length,
1599
+ continuationToken
1600
+ });
1601
+ // Create and return the page result
1602
+ return PaginationManager.createPaginatedResponse({
1603
+ pageInfo: {
1604
+ hasMore,
1605
+ totalCount,
1606
+ currentPage: params.pageNumber,
1607
+ pageSize: params.pageSize,
1608
+ continuationToken
1609
+ },
1610
+ type: paginationType,
1611
+ }, items);
1612
+ }
1613
+ /**
1614
+ * Determines if there are more pages based on pagination type and metadata
1615
+ */
1616
+ determineHasMorePages(paginationType, info) {
1617
+ switch (paginationType) {
1618
+ case PaginationType.OFFSET:
1619
+ const effectivePageSize = info.pageSize ?? DEFAULT_PAGE_SIZE;
1620
+ // If totalCount is available, use it for precise calculation
1621
+ if (info.totalCount !== undefined) {
1622
+ return (info.currentPage * effectivePageSize) < info.totalCount;
1623
+ }
1624
+ // Fallback when totalCount is not available
1625
+ // NOTE: This code path should rarely be executed as the APIs typically return totalCount
1626
+ return info.itemsCount === effectivePageSize;
1627
+ case PaginationType.TOKEN:
1628
+ return !!info.continuationToken;
1629
+ default:
1630
+ return false;
1631
+ }
1632
+ }
1633
+ }
1634
+ _BaseService_apiClient = new WeakMap();
1635
+
1636
+ /**
1637
+ * Base service for services that need folder-specific functionality.
1638
+ *
1639
+ * Extends BaseService with additional methods for working with folder-scoped resources
1640
+ * in UiPath Orchestrator. Services that work with folders (Assets, Queues) extend this class.
1641
+ *
1642
+ * @remarks
1643
+ * This class provides helper methods for making folder-scoped API calls, handling folder IDs
1644
+ * in request headers, and managing cross-folder queries.
1645
+ */
1646
+ class FolderScopedService extends BaseService {
1647
+ /**
1648
+ * Gets resources in a folder with optional query parameters
1649
+ *
1650
+ * @param endpoint - API endpoint to call
1651
+ * @param folderId - required folder ID
1652
+ * @param options - Query options
1653
+ * @param transformFn - Optional function to transform the response data
1654
+ * @returns Promise resolving to an array of resources
1655
+ */
1656
+ async _getByFolder(endpoint, folderId, options = {}, transformFn) {
1657
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
1658
+ const keysToPrefix = Object.keys(options);
1659
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
1660
+ const response = await this.get(endpoint, {
1661
+ params: apiOptions,
1662
+ headers
1663
+ });
1664
+ if (transformFn) {
1665
+ return response.data?.value.map(transformFn);
1666
+ }
1667
+ return response.data?.value;
1668
+ }
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 Queue Service Endpoints
1681
+ */
1682
+ const QUEUE_ENDPOINTS = {
1683
+ GET_BY_FOLDER: `${ORCHESTRATOR_BASE}/odata/QueueDefinitions`,
1684
+ GET_ALL: `${ORCHESTRATOR_BASE}/odata/QueueDefinitions/UiPath.Server.Configuration.OData.GetQueuesAcrossFolders`,
1685
+ GET_BY_ID: (id) => `${ORCHESTRATOR_BASE}/odata/QueueDefinitions(${id})`,
1686
+ };
1687
+
1688
+ /**
1689
+ * Maps fields for Queue entities to ensure consistent naming
1690
+ */
1691
+ const QueueMap = {
1692
+ creationTime: 'createdTime',
1693
+ organizationUnitId: 'folderId',
1694
+ organizationUnitFullyQualifiedName: 'folderName'
1695
+ };
1696
+
1697
+ /**
1698
+ * SDK Telemetry constants
1699
+ */
1700
+ // Connection string placeholder that will be replaced during build
1701
+ 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";
1702
+ // SDK Version placeholder
1703
+ const SDK_VERSION = "1.0.0";
1704
+ const VERSION = "Version";
1705
+ const SERVICE = "Service";
1706
+ const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
1707
+ const CLOUD_TENANT_NAME = "CloudTenantName";
1708
+ const CLOUD_URL = "CloudUrl";
1709
+ const CLOUD_CLIENT_ID = "CloudClientId";
1710
+ const CLOUD_REDIRECT_URI = "CloudRedirectUri";
1711
+ const APP_NAME = "ApplicationName";
1712
+ const CLOUD_ROLE_NAME = "uipath-ts-sdk";
1713
+ // Service and logger names
1714
+ const SDK_SERVICE_NAME = "UiPath.TypeScript.Sdk";
1715
+ const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
1716
+ // Event names
1717
+ const SDK_RUN_EVENT = "Sdk.Run";
1718
+ // Default value for unknown/empty attributes
1719
+ const UNKNOWN = "";
1720
+
1721
+ /**
1722
+ * Log exporter that sends ALL logs as Application Insights custom events
1723
+ */
1724
+ class ApplicationInsightsEventExporter {
1725
+ constructor(connectionString) {
1726
+ this.connectionString = connectionString;
1727
+ }
1728
+ export(logs, resultCallback) {
1729
+ try {
1730
+ logs.forEach(logRecord => {
1731
+ this.sendAsCustomEvent(logRecord);
1732
+ });
1733
+ resultCallback({ code: 0 });
1734
+ }
1735
+ catch (error) {
1736
+ console.debug('Failed to export logs to Application Insights:', error);
1737
+ resultCallback({ code: 2, error });
1738
+ }
1739
+ }
1740
+ shutdown() {
1741
+ return Promise.resolve();
1742
+ }
1743
+ sendAsCustomEvent(logRecord) {
1744
+ // Get event name from body or attributes
1745
+ const eventName = logRecord.body || SDK_RUN_EVENT;
1746
+ const payload = {
1747
+ name: 'Microsoft.ApplicationInsights.Event',
1748
+ time: new Date().toISOString(),
1749
+ iKey: this.extractInstrumentationKey(),
1750
+ data: {
1751
+ baseType: 'EventData',
1752
+ baseData: {
1753
+ ver: 2,
1754
+ name: eventName,
1755
+ properties: this.convertAttributesToProperties(logRecord.attributes || {})
1756
+ }
1757
+ },
1758
+ tags: {
1759
+ 'ai.cloud.role': CLOUD_ROLE_NAME,
1760
+ 'ai.cloud.roleInstance': SDK_VERSION
1761
+ }
1762
+ };
1763
+ this.sendToApplicationInsights(payload);
1764
+ }
1765
+ extractInstrumentationKey() {
1766
+ const match = this.connectionString.match(/InstrumentationKey=([^;]+)/);
1767
+ return match ? match[1] : '';
1768
+ }
1769
+ convertAttributesToProperties(attributes) {
1770
+ const properties = {};
1771
+ Object.entries(attributes || {}).forEach(([key, value]) => {
1772
+ properties[key] = String(value);
1773
+ });
1774
+ return properties;
1775
+ }
1776
+ async sendToApplicationInsights(payload) {
1777
+ try {
1778
+ const ingestionEndpoint = this.extractIngestionEndpoint();
1779
+ if (!ingestionEndpoint) {
1780
+ console.debug('No ingestion endpoint found in connection string');
1781
+ return;
1782
+ }
1783
+ const url = `${ingestionEndpoint}/v2/track`;
1784
+ const response = await fetch(url, {
1785
+ method: 'POST',
1786
+ headers: {
1787
+ 'Content-Type': 'application/json',
1788
+ },
1789
+ body: JSON.stringify(payload)
1790
+ });
1791
+ if (!response.ok) {
1792
+ console.debug(`Failed to send event telemetry: ${response.status} ${response.statusText}`);
1793
+ }
1794
+ }
1795
+ catch (error) {
1796
+ console.debug('Error sending event telemetry to Application Insights:', error);
1797
+ }
1798
+ }
1799
+ extractIngestionEndpoint() {
1800
+ const match = this.connectionString.match(/IngestionEndpoint=([^;]+)/);
1801
+ return match ? match[1] : '';
1802
+ }
1803
+ }
1804
+ /**
1805
+ * Singleton telemetry client
1806
+ */
1807
+ class TelemetryClient {
1808
+ constructor() {
1809
+ this.isInitialized = false;
1810
+ }
1811
+ static getInstance() {
1812
+ if (!TelemetryClient.instance) {
1813
+ TelemetryClient.instance = new TelemetryClient();
1814
+ }
1815
+ return TelemetryClient.instance;
1816
+ }
1817
+ /**
1818
+ * Initialize telemetry
1819
+ */
1820
+ initialize(config) {
1821
+ if (this.isInitialized) {
1822
+ return;
1823
+ }
1824
+ this.isInitialized = true;
1825
+ if (config) {
1826
+ this.telemetryContext = config;
1827
+ }
1828
+ try {
1829
+ const connectionString = this.getConnectionString();
1830
+ if (!connectionString) {
1831
+ return;
1832
+ }
1833
+ this.setupTelemetryProvider(connectionString);
1834
+ }
1835
+ catch (error) {
1836
+ // Silent failure - telemetry errors shouldn't break functionality
1837
+ console.debug('Failed to initialize OpenTelemetry:', error);
1838
+ }
1839
+ }
1840
+ getConnectionString() {
1841
+ const connectionString = CONNECTION_STRING;
1842
+ return connectionString;
1843
+ }
1844
+ setupTelemetryProvider(connectionString) {
1845
+ const exporter = new ApplicationInsightsEventExporter(connectionString);
1846
+ const processor = new sdkLogs.BatchLogRecordProcessor(exporter);
1847
+ this.logProvider = new sdkLogs.LoggerProvider({
1848
+ processors: [processor]
1849
+ });
1850
+ this.logger = this.logProvider.getLogger(SDK_LOGGER_NAME);
1851
+ }
1852
+ /**
1853
+ * Track a telemetry event
1854
+ */
1855
+ track(eventName, name, extraAttributes = {}) {
1856
+ try {
1857
+ // Skip if logger not initialized
1858
+ if (!this.logger) {
1859
+ return;
1860
+ }
1861
+ const finalDisplayName = name || eventName;
1862
+ const attributes = this.getEnrichedAttributes(extraAttributes, eventName);
1863
+ // Emit as log
1864
+ this.logger.emit({
1865
+ body: finalDisplayName,
1866
+ attributes: attributes,
1867
+ timestamp: Date.now(),
1868
+ });
1869
+ }
1870
+ catch (error) {
1871
+ // Silent failure
1872
+ console.debug('Failed to track telemetry event:', error);
1873
+ }
1874
+ }
1875
+ /**
1876
+ * Get enriched attributes for telemetry events
1877
+ */
1878
+ getEnrichedAttributes(extraAttributes, eventName) {
1879
+ const attributes = {
1880
+ ...extraAttributes,
1881
+ [APP_NAME]: SDK_SERVICE_NAME,
1882
+ [VERSION]: SDK_VERSION,
1883
+ [SERVICE]: eventName,
1884
+ [CLOUD_URL]: this.createCloudUrl(),
1885
+ [CLOUD_ORGANIZATION_NAME]: this.telemetryContext?.orgName || UNKNOWN,
1886
+ [CLOUD_TENANT_NAME]: this.telemetryContext?.tenantName || UNKNOWN,
1887
+ [CLOUD_REDIRECT_URI]: this.telemetryContext?.redirectUri || UNKNOWN,
1888
+ [CLOUD_CLIENT_ID]: this.telemetryContext?.clientId || UNKNOWN,
1889
+ };
1890
+ return attributes;
1891
+ }
1892
+ /**
1893
+ * Create cloud URL from base URL, organization ID, and tenant ID
1894
+ */
1895
+ createCloudUrl() {
1896
+ const baseUrl = this.telemetryContext?.baseUrl;
1897
+ const orgId = this.telemetryContext?.orgName;
1898
+ const tenantId = this.telemetryContext?.tenantName;
1899
+ if (!baseUrl || !orgId || !tenantId) {
1900
+ return UNKNOWN;
1901
+ }
1902
+ return `${baseUrl}/${orgId}/${tenantId}`;
1903
+ }
1904
+ }
1905
+ // Export singleton instance
1906
+ const telemetryClient = TelemetryClient.getInstance();
1907
+
1908
+ /**
1909
+ * SDK Track decorator and function for telemetry
1910
+ */
1911
+ /**
1912
+ * Common tracking logic shared between method and function decorators
1913
+ */
1914
+ function createTrackedFunction(originalFunction, nameOrOptions, fallbackName, opts) {
1915
+ return function (...args) {
1916
+ // Determine if we should track this call
1917
+ let shouldTrack = true;
1918
+ if (opts.condition !== undefined) {
1919
+ if (typeof opts.condition === 'function') {
1920
+ shouldTrack = opts.condition.apply(this, args);
1921
+ }
1922
+ else {
1923
+ shouldTrack = opts.condition;
1924
+ }
1925
+ }
1926
+ // Track the event if enabled
1927
+ if (shouldTrack) {
1928
+ // Use the full name provided in the decorator (e.g., "Queue.GetAll")
1929
+ const serviceMethod = typeof nameOrOptions === 'string'
1930
+ ? nameOrOptions
1931
+ : fallbackName;
1932
+ // Use 'Sdk.Run' as the name and serviceMethod as the service
1933
+ telemetryClient.track(serviceMethod, SDK_RUN_EVENT, opts.attributes);
1934
+ }
1935
+ // Execute the original function
1936
+ return originalFunction.apply(this, args);
1937
+ };
1938
+ }
1939
+ /**
1940
+ * Track decorator that can be used to automatically track function calls
1941
+ *
1942
+ * Usage:
1943
+ * @track("Service.Method")
1944
+ * function myFunction() { ... }
1945
+ *
1946
+ * @track("Queue.GetAll")
1947
+ * async getAll() { ... }
1948
+ *
1949
+ * @track("Tasks.Create")
1950
+ * async create() { ... }
1951
+ *
1952
+ * @track("Assets.Update", { condition: false })
1953
+ * function myFunction() { ... }
1954
+ *
1955
+ * @track("Processes.Start", { attributes: { customProp: "value" } })
1956
+ * function myFunction() { ... }
1957
+ */
1958
+ function track(nameOrOptions, options) {
1959
+ return function decorator(_target, propertyKey, descriptor) {
1960
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : {};
1961
+ if (descriptor && typeof descriptor.value === 'function') {
1962
+ // Method decorator
1963
+ descriptor.value = createTrackedFunction(descriptor.value, nameOrOptions, propertyKey || 'unknown_method', opts);
1964
+ return descriptor;
1965
+ }
1966
+ // Function decorator
1967
+ return (originalFunction) => createTrackedFunction(originalFunction, nameOrOptions, originalFunction.name || 'unknown_function', opts);
1968
+ };
1969
+ }
1970
+
1971
+ /**
1972
+ * Service for interacting with UiPath Orchestrator Queues API
1973
+ */
1974
+ class QueueService extends FolderScopedService {
1975
+ /**
1976
+ * Gets all queues across folders with optional filtering and folder scoping
1977
+ *
1978
+ * The method returns either:
1979
+ * - An array of queues (when no pagination parameters are provided)
1980
+ * - A paginated result with navigation cursors (when any pagination parameter is provided)
1981
+ *
1982
+ * @param options - Query options including optional folderId
1983
+ * @returns Promise resolving to an array of queues or paginated result
1984
+ *
1985
+ * @example
1986
+ * ```typescript
1987
+ * import { Queues } from '@uipath/uipath-typescript/queues';
1988
+ *
1989
+ * const queues = new Queues(sdk);
1990
+ *
1991
+ * // Standard array return
1992
+ * const allQueues = await queues.getAll();
1993
+ *
1994
+ * // Get queues within a specific folder
1995
+ * const folderQueues = await queues.getAll({
1996
+ * folderId: 123
1997
+ * });
1998
+ *
1999
+ * // Get queues with filtering
2000
+ * const filteredQueues = await queues.getAll({
2001
+ * filter: "name eq 'MyQueue'"
2002
+ * });
2003
+ *
2004
+ * // First page with pagination
2005
+ * const page1 = await queues.getAll({ pageSize: 10 });
2006
+ *
2007
+ * // Navigate using cursor
2008
+ * if (page1.hasNextPage) {
2009
+ * const page2 = await queues.getAll({ cursor: page1.nextCursor });
2010
+ * }
2011
+ *
2012
+ * // Jump to specific page
2013
+ * const page5 = await queues.getAll({
2014
+ * jumpToPage: 5,
2015
+ * pageSize: 10
2016
+ * });
2017
+ * ```
2018
+ */
2019
+ async getAll(options) {
2020
+ // Transformation function for queues
2021
+ const transformQueueResponse = (queue) => transformData(pascalToCamelCaseKeys(queue), QueueMap);
2022
+ return PaginationHelpers.getAll({
2023
+ serviceAccess: this.createPaginationServiceAccess(),
2024
+ getEndpoint: (folderId) => folderId ? QUEUE_ENDPOINTS.GET_BY_FOLDER : QUEUE_ENDPOINTS.GET_ALL,
2025
+ getByFolderEndpoint: QUEUE_ENDPOINTS.GET_BY_FOLDER,
2026
+ transformFn: transformQueueResponse,
2027
+ pagination: {
2028
+ paginationType: PaginationType.OFFSET,
2029
+ itemsField: ODATA_PAGINATION.ITEMS_FIELD,
2030
+ totalCountField: ODATA_PAGINATION.TOTAL_COUNT_FIELD,
2031
+ paginationParams: {
2032
+ pageSizeParam: ODATA_OFFSET_PARAMS.PAGE_SIZE_PARAM,
2033
+ offsetParam: ODATA_OFFSET_PARAMS.OFFSET_PARAM,
2034
+ countParam: ODATA_OFFSET_PARAMS.COUNT_PARAM
2035
+ }
2036
+ }
2037
+ }, options);
2038
+ }
2039
+ /**
2040
+ * Gets a single queue by ID
2041
+ *
2042
+ * @param id - Queue ID
2043
+ * @param folderId - Required folder ID
2044
+ * @returns Promise resolving to a queue definition
2045
+ *
2046
+ * @example
2047
+ * ```typescript
2048
+ * import { Queues } from '@uipath/uipath-typescript/queues';
2049
+ *
2050
+ * const queues = new Queues(sdk);
2051
+ *
2052
+ * // Get queue by ID
2053
+ * const queue = await queues.getById(123, 456);
2054
+ * ```
2055
+ */
2056
+ async getById(id, folderId, options = {}) {
2057
+ const headers = createHeaders({ [FOLDER_ID]: folderId });
2058
+ const keysToPrefix = Object.keys(options);
2059
+ const apiOptions = addPrefixToKeys(options, ODATA_PREFIX, keysToPrefix);
2060
+ const response = await this.get(QUEUE_ENDPOINTS.GET_BY_ID(id), {
2061
+ headers,
2062
+ params: apiOptions
2063
+ });
2064
+ return transformData(pascalToCamelCaseKeys(response.data), QueueMap);
2065
+ }
2066
+ }
2067
+ __decorate([
2068
+ track('Queues.GetAll')
2069
+ ], QueueService.prototype, "getAll", null);
2070
+ __decorate([
2071
+ track('Queues.GetById')
2072
+ ], QueueService.prototype, "getById", null);
2073
+
2074
+ exports.QueueService = QueueService;
2075
+ exports.Queues = QueueService;