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

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