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