@uipath/uipath-typescript 1.0.0-beta.17 → 1.0.0

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