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