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